The basic thing is to know how to start a task.
1. Task Class Constructors
Use the constructor of the task class. When instantiating a task object, the task does not run immediately, but instead specifies the created state. The start () method of the task class is then invoked to initiate the task. When using the task class, you can also call the runsynchronously () method In addition to the start () method. This way, the task starts, but it is called at the same time. By default, tasks are run asynchronously.
The constructor of the task class receives a delegate with no parameter, no return value:
New Task (Taskmethod);
2:task. Start ();
Here is the Taskmethod method:
void Taskmethod ()
2: {
3: For (int i = 0; i < ten; i++)
4: {
5: Console.WriteLine (String.Format ("Running in a" task.) Task ID: {0} ", Task.currentid));
6: Thread.Sleep (500);
7: }
8:}
Method uses the Task.currentid property to obtain the current task ID. Here is the main thread:
void Main (string[] args)
2: {
3: new Task (Taskmethod);
4: task. Start ();
6: For (int i = 0; i < ten; i++)
7: {
8: Console.WriteLine ("Running in Main thread.");
9: Thread.Sleep (500);
Ten: }
11:
: Console.read ();
13:}
If you are passing a parameter to a thread, the overload provided by the task constructor can pass in an argument of type object:
"Hello World");
2:task. Start ();
Here is the threading method with the parameter:
void Taskmethodwithparameter (object param)
2: {
3: For (int i = 0; i < ten; i++)
4: {
5: Console.WriteLine (String.Format ("Running in a" task.) Parameter: {0} ", param));
6: Thread.Sleep (500);
7: }
8:}
2, TaskFactory class
Using the instantiated TaskFactory class, in which the Taskmethod method is passed to the StartNew () method, the task is started immediately.
New TaskFactory ();
2:TF. StartNew (Taskmethod);
3. Task.factory Properties
The task class provides a factory static property that returns a TaskFactory object.
1:task Task = Task.Factory.StartNew (Taskmethod);
How to implement C # asynchronous Programming (4)--task tasks