FA C# Async 自动流程
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;
}
}
}
输出:
去上班
吃早餐
上班中...
摸鱼
下班
去上班
吃早餐
上班中...
摸鱼
下班
去上班
吃早餐
上班中...
摸鱼
停机:第二步失败
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了