内容目录
using System;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
async Task Main()
{
Task<int> task = CreateTask();
int result = await task;
}
Task<int> CreateTask()
{
// Create an asynchronous task method builder
AsyncTaskMethodBuilder<int> builder = AsyncTaskMethodBuilder<int>.Create();
// Get the state machine from the builder
var stateMachine = new AsyncStateMachine(builder);
// Set the builder to the awaiting state
stateMachine.MoveNext();
// Return the asynchronous task
return builder.Task;
}
// Define the asynchronous state machine
struct AsyncStateMachine : IAsyncStateMachine
{
private AsyncTaskMethodBuilder<int> _builder;
private int _result;
public AsyncStateMachine(AsyncTaskMethodBuilder<int> builder)
{
_builder = builder;
_result = 0;
}
public void MoveNext()
{
try
{
// Perform an asynchronous operation, here it simulates a delay of 2 seconds
Task.Delay(2000).Wait();
// Set the result of the asynchronous task
_result = 42;
// Set the result, indicating task completion
_builder.SetResult(_result);
}
catch (Exception ex)
{
// Exception handling
_builder.SetException(ex);
}
}
public void SetStateMachine(IAsyncStateMachine stateMachine)
{
// Not used, no handling needed
}
}
文章评论