有不明白的地方欢迎入群 347636249 探讨
//=========================创建和运行任务=========================
Invoke (() => {
System.Threading.Thread.Sleep (1000);
Tools.Alert ("after 1 second you see");
}, 100);
//=========================显示创建和运行任务=========================
//不返回任务
var task = new System.Threading.Tasks.Task (() => {
System.Threading.Thread.Sleep (1000);
});
task.Start ();
//返回任务
var task1 = new System.Threading.Tasks.Task<int> (() => {
System.Threading.Thread.Sleep (1000);
return 100;
});
task1.Start ();
Tools.Alert (task1.Result.ToString ());
//=========================延续任务=========================
System.Threading.Tasks.Task<int> TaskA = new System.Threading.Tasks.Task<int> (() => {
return DateTime.Now.Year;
});
System.Threading.Tasks.Task<String> TaskB = TaskA.ContinueWith ((a) => {
return String.Format ("今年是{0}年", a.Result);
});
TaskA.Start ();
Console.WriteLine(TaskB.Result);
//=========================多任务延续=========================
System.Threading.Tasks.Task<int>[] tasks = new System.Threading.Tasks.Task<int>[2];
tasks [0] = new System.Threading.Tasks.Task<int> (() => {
return DateTime.Now.Year;
});
tasks [1] = new System.Threading.Tasks.Task<int> (() => {
return DateTime.Now.Month;
});
var continuation = System.Threading.Tasks.Task.Factory.ContinueWhenAll (tasks, (antecedents) => {
string r = string.Format ("现在是{0}年{1}月", antecedents [0].Result, antecedents [1].Result);
Console.WriteLine (r);
});
tasks [0].Start ();
tasks [1].Start ();
continuation.Wait ();
//=======================嵌套任务和子任务======================
/*
父任务是不等待子任务完成的,父任务不传播子任务引发的异常,父级状态不依赖于子状态。
*/
var parent = System.Threading.Tasks.Task.Factory.StartNew (() => {
Console.WriteLine ("父任务");
var child = System.Threading.Tasks.Task.Factory.StartNew (() => {
System.Threading.Thread.Sleep (5000);
Console.WriteLine ("子任务");
});
});
//=======================任务取消======================
/*
1.简单从委托中返回。其实在多数情况下这样已经够了。但是这样取消的任务实例不
会转为Canceled状态而是转为RanToCompletion状态
2.引发 OperationCanceledException
*/
var tokenSource = new System.Threading.CancellationTokenSource ();
System.Threading.CancellationToken ct = tokenSource.Token;
var task = System.Threading.Tasks.Task.Factory.StartNew (() => {
ct.ThrowIfCancellationRequested ();
bool moreToDo = true;
while (moreToDo) {
if (ct.IsCancellationRequested) {
ct.ThrowIfCancellationRequested ();
}
}
}, tokenSource.Token);
tokenSource.Cancel();
try
{
task.Wait();
}
catch (AggregateException e)
{
foreach (var v in e.InnerExceptions)
Console.WriteLine(e.Message + " " + v.Message);
}
parent.Wait();
Console.WriteLine("大家都完了.");