1.通过 TaskScheduler + ContinuWith 实现异步更新UI
private readonly TaskScheduler scheduler;
private CancellationTokenSource cts;
// 当前GUI调度器上下文
scheduler = TaskScheduler.FromCurrentSynchronizationContext();
// 具体任务
private Int32 Sum(CancellationToken token,Int32 n)
{
Int32 sum = 0;
for (; n > 0; n--)
{
// 取消任务
token.ThrowIfCancellationRequested();
checked
{ sum += n; }
//Console.WriteLine(sum);
Thread.Sleep(10);
var i = 0;
var j = n / i;
}
return sum;
}
private void btnStart_Click(object sender,EventArgs e)
{
txtResult.Text = "开始执行";
cts = new CancellationTokenSource();
// 开始执行任务(CPU密集计算)
var t = Task.Run(() => Sum(cts.Token,100),cts.Token);
t.ContinueWith(t => txtResult.Text = $"计算结果:{t.Result}",
CancellationToken.None,TaskContinuationOptions.OnlyOnRanToCompletion,
scheduler);
t.ContinueWith(t => txtResult.Text = $"取消",
CancellationToken.None,TaskContinuationOptions.OnlyOnCanceled,
scheduler);
t.ContinueWith(t => txtResult.Text = $"{t.Exception.GetType().Name}:{t.Exception.Message}",
CancellationToken.None,TaskContinuationOptions.OnlyOnFaulted,
scheduler);
}
private void btnStop_Click(object sender,EventArgs e)
{
if (cts != null)
cts.Cancel();
}
2.同时发起多个IO请求,完成一个处理一个
// 发起大量异步客户端请求:保存每个客户端的Task<Stirng>
List<Task<String>> reqeusts = new List<Task<String>>(1000);
for(var n = 0; n < reqeusst.Capacity; n++){
// 发起异步IO请求
reqeusts.Add(xxxAsync());
}
// 每个任务完成都继续
while(reqeusts.Count>0){
// 顺序处理每个完成的响应
Task<String> response = await Task.WhenAny(reqeusts);
reqeusts.Remove(response);// 从集合中删除完成的任务
// 处理一个响应
Console.WriteLine(response.result);
}
3.同时发起多个IO请求,全部完成统一处理
// 发起大量异步客户端请求:保存每个客户端的Task<Stirng>
List<Task<String>> reqeusts = new List<Task<String>>(1000);
for(var n = 0; n < reqeusst.Capacity; n++){
// 发起异步IO请求
reqeusts.Add(xxxAsync());
}
// 异步地等待所有客户端请求完成
// 注意:如果1个以上的任务抛出异常,WhenAll 重新抛出最后一个抛出的异常
String[] responses = await Task.WhenAll(requests);
// 处理所有响应
for(var n = 0; n < responses.Capacity; n++){
Console.WriteLine(responses[n]);
}