内容目录
using System;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
async Task Main()
{
Task<int> task = CreateTask();
int result = await task;
}
Task<int> CreateTask()
{
// 创建一个异步任务方法构建器
AsyncTaskMethodBuilder<int> builder = AsyncTaskMethodBuilder<int>.Create();
// 获取构建器的状态机
var stateMachine = new AsyncStateMachine(builder);
// 将构建器设置为等待状态
stateMachine.MoveNext();
// 返回异步任务
return builder.Task;
}
// 定义异步状态机
struct AsyncStateMachine : IAsyncStateMachine
{
private AsyncTaskMethodBuilder<int> _builder;
private int _result;
public AsyncStateMachine(AsyncTaskMethodBuilder<int> builder)
{
_builder = builder;
_result = 0;
}
public void MoveNext()
{
try
{
// 执行异步操作,这里以延迟 2 秒为例
Task.Delay(2000).Wait();
// 设置异步任务的结果
_result = 42;
// 设置值,任务结束
_builder.SetResult(_result);
}
catch (Exception ex)
{
// 异常处理
_builder.SetException(ex);
}
}
public void SetStateMachine(IAsyncStateMachine stateMachine)
{
// 用不到,不处理
}
}
文章评论