First, basic use
The difference between Thread, ThreadPool and Task
Task was added in .NET4.0 and has similar functions to the thread pool ThreadPool. When using Task to start a new task , the thread will be called from the thread pool, and Thread will create a new thread every time it is instantiated.
If it is a long-term operation, please use
TaskCreationOptions.LongRunning in the Task (Acton, TaskCreationOptions) constructor to imply the task scheduler and put this thread Execute on non-thread pool
The second and fourth startup methods
1) Start through start, new one Task, where the parameter is an Action
class Program
{
static void Main(string[] args)
{
Task t = new Task(DoA);
t.Start();
Console.ReadKey();
}
static void DoA()
{
for (int i = 0; i < 100; i++)
{
Console.WriteLine("i={0}\n", i);
}
}
}
Copy after login
2) Run directly through Run, accept The parameter is an Action, and the return object is a Task
static void Main(string[] args)
{
Task.Run(() =>
{
for (int i = 0; i < 50; i++)
{
Console.WriteLine("i={0}",i);
}
});
Console.ReadKey();
}
Copy after login
3) Thread with return parameters
Task<int> task = Task.Run<int>(() =>
{
int sum = 0;
for (int i = 0; i < 50; i++)
{
sum += 1;
}
return sum;
});
int result = task.Result;
Console.WriteLine("运算结果是:{0}",result);//输出50
Console.ReadKey();
Copy after login
4) Through Task.Factory
Task t = Task.Factory.StartNew(() =>
{
for (int i = 0; i < 10; i++)
{
Console.WriteLine("i={0}", i);
}
});
Copy after login
The above is the detailed content of Task usage startup method example. For more information, please follow other related articles on the PHP Chinese website!
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn