• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

《C#并行编程高级教程》第3章命令式任务并行笔记

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

Task的使用

var t1 = new Task(() => GenerateAESKeys());
var t2 = new Task(() => GenerateMD5Hashes());
// Start the tasks
t1.Start();
t2.Start();
// Wait for all the tasks to finish
Task.WaitAll(t1, t2);

等待超时

// Wait for all the tasks to finish with a 1 second timeout
if (!Task.WaitAll(new Task[] { t1, t2 }, 1000))
{
    //...
}

取消任务

使用CancellationToken,在取消时会抛出OperationCanceledException异常
private static void GenerateAESKeysCancel(System.Threading.CancellationToken ct)
{
    ct.ThrowIfCancellationRequested();
    var aesM = new AesManaged();
    for (int i = 1; i <= NUM_AES_KEYS; i++)
    {
        aesM.GenerateKey();
        byte[] result = aesM.Key;
        string hexString = ConvertToHexString(result);
        // Console.WriteLine("AES KEY: {0} ", hexString);
        ct.ThrowIfCancellationRequested();
    }
}

异常处理

try
{
    //...
}
catch (AggregateException ex)
{
    foreach (Exception innerEx in ex.InnerExceptions)
    {
        Debug.WriteLine(innerEx.ToString());
        // Do something considering the innerEx Exception
    }
}

任务返回值

使用Task<TResult>创建的任务在Reault属性中可以保存返回值
var cts = new System.Threading.CancellationTokenSource();
var ct = cts.Token;
var t1 = Task.Factory.StartNew(
    () => GenerateAESKeysWithCharPrefix(ct, 'A'), ct);
t1.Wait();
for (int i = 0; i < t1.Result.Count; i++)
{
    Console.WriteLine(t1.Result[i]);
}
private static List<String> GenerateAESKeysWithCharPrefix(
    System.Threading.CancellationToken ct, char prefix)
{
    var aesM = new AesManaged();
    var keysList = new List<String>();
    for (int i = 1; i <= NUM_AES_KEYS; i++)
    {
        aesM.GenerateKey();
        byte[] result = aesM.Key;
        string hexString = ConvertToHexString(result);
        if (hexString[0] == prefix)
        {
            keysList.Add(hexString);
        }
        if (ct.IsCancellationRequested)
        {
            ct.ThrowIfCancellationRequested();
        }
    }
    return keysList;
}

串联任务

var cts = new System.Threading.CancellationTokenSource();
var ct = cts.Token;
var t1 = Task.Factory.StartNew(
    () => GenerateAESKeysWithCharPrefix(ct, 'A'), ct);
var t2 = t1.ContinueWith((t) =>
{
    for (int i = 0; i < t.Result.Count; i++)
    {
        Console.WriteLine(t.Result[i]);
    }
});
 






鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C#文件操作大全发布时间:2022-07-14
下一篇:
圆角按钮c#发布时间:2022-07-14
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap