C#
Async 方式
簡單的流程測試:
去上班
吃早餐
上班中...
摸魚
下班
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
MyWorkStep ms = new MyWorkStep();
ms.AutoFlag = true;
ms.DoRun();
Console.ReadKey();
}
}
enum WorkStep
{
One,
Two,
Three,
}
enum StepResult
{
OK,
Error
}
class MyWorkStep
{
public bool AutoFlag = false;
private ulong _count = 0;
private WorkStep _currentStep = WorkStep.One;
public void DoRun()
{
while (AutoFlag)
{
switch (_currentStep)
{
case WorkStep.One:
Task<StepResult> firstRes = DoFirstAsync();
Task<StepResult> thirdRes = DoThirdAsync();
if (firstRes.Result == StepResult.OK && thirdRes.Result == StepResult.OK)
{
_currentStep = WorkStep.Two;
break;
}
Console.WriteLine("第一步失敗");
AutoFlag = false;
return;
case WorkStep.Two:
Task<StepResult> secondRes = DoSecondAsync();
Task<StepResult> fishRes = DoFish();
if (secondRes.Result == StepResult.OK && fishRes.Result == StepResult.OK)
{
_currentStep = WorkStep.Three;
break;
}
if (secondRes.Result == StepResult.Error)
{
Console.Write("\n停機:");
AutoFlag = false;
}
Console.WriteLine("第二步失敗");
return;
case WorkStep.Three:
Task<StepResult> fourthRes = DoFourthAsync();
if (fourthRes.Result == StepResult.OK)
{
_currentStep = WorkStep.One;
Console.WriteLine();
break;
}
Console.WriteLine("第三部失敗");
return;
}
}
}
private async Task<StepResult> DoFirstAsync()
{
Console.WriteLine("去上班");
StepResult res = await Task.Run(() =>
{
Thread.Sleep(2000);
return StepResult.OK;
});
return res;
}
private static int count = 0;
private async Task<StepResult> DoSecondAsync()
{
Console.WriteLine("上班中...");
StepResult res = await Task.Run(() =>
{
count++;
Thread.Sleep(1500);
if (count < 3)
return StepResult.OK;
return StepResult.Error;
});
return res;
}
private async Task<StepResult> DoThirdAsync()
{
Console.WriteLine("吃早餐");
StepResult res = await Task.Run(() =>
{
Thread.Sleep(1500);
return StepResult.OK;
});
return res;
}
private async Task<StepResult> DoFish()
{
Console.WriteLine("摸魚");
StepResult res = await Task.Run(() =>
{
Thread.Sleep(1000);
return StepResult.OK;
});
return res;
}
private async Task<StepResult> DoFourthAsync()
{
Console.WriteLine("下班");
StepResult res = await Task.Run(() =>
{
Thread.Sleep(1000);
return StepResult.OK;
});
return res;
}
}
}
去上班
吃早餐
上班中...
摸魚
下班
去上班
吃早餐
上班中...
摸魚
下班
去上班
吃早餐
上班中...
摸魚
停機:第二步失敗