Task Parallel Library01, basic usage, parallellibrary01
We know that each application is a process, and a process has multiple threads. The Task Parallel Library provides strong support for asynchronous and multi-threaded programming. It allows a main thread to run simultaneously and other threads or tasks to run simultaneously. Basic usage of this article.
Basic usage
The Taks constructor receives an Action, that is, a delegate.
static void Main(string[] args)
{ var t1 = new Task(() =>
{Console. WriteLine ("Task 1 starts "); Thread.Sleep(1000);
Console. WriteLine ("Task 1 ends "); });
t1.Start();
Console.ReadKey();
}
If you put the method out.
static void Main(string[] args)
{ var t1 = new Task(() => DoSth(1,2000));
t1.Start();
Console.ReadKey();
}
static void DoSth(int id, int sleepTime)
{Console. WriteLine ("task {0} start", id ); Thread.Sleep(sleepTime);
Console. WriteLine ("task {0} ended", id ); }
If multiple tasks are executed simultaneously.
static void Main(string[] args)
{ var t1 = new Task(() => DoSth(1,2000));
t1.Start();
var t2 = new Task(() => DoSth(2, 1500));
t2.Start();
var t3 = new Task(() => DoSth(3, 3000));
t3.Start();
Console.ReadKey();
}
If there are many tasks, it is very troublesome to start each Task manually. The Task Parallel Library has prepared a Task factory for us.
static void Main(string[] args)
{ var t1 = Task.Factory.StartNew(() => DoSth(1, 2000));
var t2 = Task.Factory.StartNew(() => DoSth(2, 1500));
var t3 = Task.Factory.StartNew(() => DoSth(3, 3000));
Console.ReadKey();
}
If you want to execute a task immediately after the end of a task, you can use the ContinueWith method.
static void Main(string[] args)
{ var t1 = Task.Factory.StartNew(() => DoSth(1, 2000)).ContinueWith((pre)=> DoOtherThing(4,2000));
var t2 = Task.Factory.StartNew(() => DoSth(2, 1500));
var t3 = Task.Factory.StartNew(() => DoSth(3, 3000));
Console.ReadKey();
}
static void DoSth(int id, int sleepTime)
{Console. WriteLine ("task {0} start", id ); Thread.Sleep(sleepTime);
Console. WriteLine ("task {0} ended", id ); }
static void DoOtherThing(int id, int sleepTime)
{Console. WriteLine ("other tasks {0} start", id ); Thread.Sleep(sleepTime);
Console. WriteLine ("other task {0} ended", id ); }
If you want to wait for all tasks to be completed, use the WaitAll method.
static void Main(string[] args)
{ var t1 = Task.Factory.StartNew(() => DoSth(1, 2000));
var t2 = Task.Factory.StartNew(() => DoSth(2, 1500));
var t3 = Task.Factory.StartNew(() => DoSth(3, 3000));
var taskList = new List<Task> {t1, t2, t3}; Task.WaitAll(taskList.ToArray());
Console. WriteLine ("I executed only after all tasks have been executed "); Console.ReadKey();
}
To manually cancel a Task, you must add the CancellationToken type parameter to the method.
static void Main(string[] args)
{ var source = new CancellationTokenSource();
try
{ var t1 =
Task.Factory.StartNew(() => DoSth(1, 1000, source.Token))
.ContinueWith((pre) => DoOtherThing(2, 2000));
source.Cancel();
}
catch (Exception ex)
{ Console.WriteLine(ex.GetType());
}
Console.WriteLine("haha"); Console.ReadKey();
}
static void DoSth(int id, int sleepTime, CancellationToken token)
{ if (token.IsCancellationRequested)
{Console. WriteLine ("task canceled "); token.ThrowIfCancellationRequested();
}
Console. WriteLine ("task {0} start", id ); Thread.Sleep(sleepTime);
Console. WriteLine ("task {0} ended", id ); }
static void DoOtherThing(int id, int sleepTime)
{Console. WriteLine ("other tasks {0} start", id ); Thread.Sleep(sleepTime);
Console. WriteLine ("other task {0} ended", id ); }
How can I obtain the returned results of a method from a Task?
static void Main(string[] args)
{Console. WriteLine ("START computing "); Task<int> t = Task.Factory.StartNew(() => Sum(1, 2));
Console. WriteLine ("waiting for results "); Console.WriteLine(t.Result);
Console.ReadKey();
}
static int Sum(int a, int b)
{ return a + b;
}
The next Task gets the return value of the previous Task.
static void Main(string[] args)
{ Task<string> firstTask = Task.Factory.StartNew<string>(() =>
{Console. WriteLine ("the first task starts "); return "hi from the one";
});
Task secondTask = firstTask.ContinueWith((prevoursTask) =>
{Console. WriteLine ("here is the second task. The returned value of the first task is {0}", prevoursTask. Result, TaskContinuationOptions. OnlyOnRanToCompletion ); });
secondTask.Wait();
Console.ReadKey();
}
Wait until all tasks are completed.
static void Main(string[] args)
{ var t1 = Task.Factory.StartNew(() =>
{Console. WriteLine ("first task "); Thread.Sleep(1000);
});
var t2 = Task.Factory.StartNew(() =>
{Console. WriteLine ("second task "); Thread.Sleep(1000);
});
var taskList = new List<Task> {t1, t2};Task. Factory. ContinueWhenAll (taskList. ToArray (), (t) =>{ Console. WriteLine ("all tasks are completed and I will come out ");}); Console.ReadKey();
}
For nested tasks.
static void Main(string[] args)
{ Task.Factory.StartNew(() =>
{ Task child = Task.Factory.StartNew(() =>
{Console. WriteLine ("I Am a subtask "); }, TaskCreationOptions.AttachedToParent);
}).Wait();
Console.ReadKey();
}
Several ways to start a Task
1. Use the Task. Factory. StartNew method.
static void Main(string[] args)
{ Task.Factory.StartNew(() => SaySth("hello")); Console.ReadKey();
}
static void SaySth(string msg)
{ Console.WriteLine(msg);
}
2. Use the Start instance method of the Task
static void Main(string[] args)
{ var t = new Task(() => SaySth("hello")); t.Start();
Console.ReadKey();
}
Or simply use the delegate.
static void Main(string[] args)
{ Task t = new Task(delegate {SaySth("hello");}); t.Start();
Console.ReadKey();
}
3. Static Task method Run
static void Main(string[] args)
{ Task t = Task.Run(() => SaySth("hello")); Console.ReadKey();
}
static void SaySth(string msg)
{ Console.WriteLine(msg);
}
Example
For example, to download a page, use the Task to start the Task in the background to download a page without affecting the current UI.
static void Main(string[] args)
{Console. WriteLine ("interface content "); Task<string> r = DownloadAsync("http://www.baidu.com"); while (!r.IsCompleted)
{ Console.Write("."); Thread.Sleep(250);
}
Console.WriteLine(r.Result);
Console.ReadKey();
}
private static string DownloadWebPage(string url)
{ WebRequest request = WebRequest.Create(url);
WebResponse response = request.GetResponse();
var reader = new StreamReader(response.GetResponseStream());
return reader.ReadToEnd();
}
private static Task<string> DownloadAsync(string url)
{ return Task.Factory.StartNew(() => DownloadWebPage(url));
}