1、C#异步模式分类
基于任务的异步模式(TAP)
基于事件的异步模式(EAP)和异步编程模型模式(APM)
2、基于任务的异步模式(TAP)
基于任务的异步模式(TAP)用单个方法表示异步操作的开始和完成。
3、基本示例
csharp
static void Main(string[] args)
{
var task = DoWork();
Console.ReadKey();
}
public static Task DoWork()
{
for (int i = 0; i < 10; i++)
{
Console.WriteLine(i);
Task.Delay(1000);
}
return Task.CompletedTask;
}
}
4、任务终止示例
csharp
static void Main(string[] args)
{
CancellationTokenSource cts = new CancellationTokenSource();
CancellationToken token = cts.Token;
var task = DoWork(token);
Thread.Sleep(100);
cts.Cancel();
Console.WriteLine("cancel..");
Console.ReadKey();
}
public static Task DoWork(CancellationToken cancellationToken)
{
while (!cancellationToken.IsCancellationRequested)
{
Console.WriteLine("wait..");
Thread.Sleep(1000);
return Task.CompletedTask;
}
return Task.FromCanceled(cancellationToken);
}
}
5、进度显示示例
csharp
static void Main(string[] args)
{
var progress = new Progress<double>(p =>
{
Console.WriteLine($"进度:{p}%");
});
var task = DoWork(progress);
Console.ReadKey();
}
public static async Task DoWork(IProgress<double> progress)
{
for(int i = 0; i <= 1000; i++)
{
await Task.Delay(10);
if(i%100 == 0)
{
double d = i/10.0;
progress?.Report(d);
}
}
}
}