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);
var t2 = new Task(() => GenerateMD5Hashes());
// Start the tasks
t1.Start();
t2.Start();
// Wait for all the tasks to finish
Task.WaitAll(t1, t2);
等待超时
))
{
//...
}
{
//...
}
取消任务
使用CancellationToken,在取消时会抛出OperationCanceledException异常
; i <= NUM_AES_KEYS; i++)
{
aesM.GenerateKey();
byte[] result = aesM.Key;
string hexString = ConvertToHexString(result);
// Console.WriteLine("AES KEY: {0} ", hexString);
ct.ThrowIfCancellationRequested();
}
}
{
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
}
}
{
//...
}
catch (AggregateException ex)
{
foreach (Exception innerEx in ex.InnerExceptions)
{
Debug.WriteLine(innerEx.ToString());
// Do something considering the innerEx Exception
}
}
任务返回值
使用Task<TResult>创建的任务在Reault属性中可以保存返回值
var cts ; i ; i ] == prefix)
{
keysList.Add(hexString);
}
if (ct.IsCancellationRequested)
{
ct.ThrowIfCancellationRequested();
}
}
return keysList;
}
{
keysList.Add(hexString);
}
if (ct.IsCancellationRequested)
{
ct.ThrowIfCancellationRequested();
}
}
return keysList;
}
串联任务
var cts ; i < t.Result.Count; i++)
{
Console.WriteLine(t.Result[i]);
}
});
{
Console.WriteLine(t.Result[i]);
}
});