repeat

stay .Net5 Under the platform , Create a console program , Pay attention to the console program Main() The method is as follows :

static async Task Main(string[] args)

The body of the method is very simple , Use Task.Run Create an immediate Task, Keep outputting threads inside id, Until the program is manually closed , The code is as follows :

code snippet 1

Click to view the code
static async Task Main(string[] args)
{
Console.WriteLine(" Main thread thread id:" + Thread.CurrentThread.ManagedThreadId);
await Task.Run(async () =>
{
while (true)
{
Console.WriteLine("Fuck World! Threads id:" + Thread.CurrentThread.ManagedThreadId);
await Task.Delay(2000);
Console.WriteLine(" Threads id:" + Thread.CurrentThread.ManagedThreadId);
}
});
}

This code runs as scheduled , And there is no need to use at the end of the program Console.ReadLine() The control program does not stop .

But if we use Task.Factory.StartNew() Replace Task.Run() Words , The program will flash by , Quit immediately .

If you use New Task() Create words , As shown in the following code :

code snippet 2

Click to view the code
var t = new Task(async () =>
{
while (true)
{
Console.WriteLine("Fuck World! Threads :" + Thread.CurrentThread.ManagedThreadId);
await Task.Delay(2000);
Console.WriteLine(" Threads id:" + Thread.CurrentThread.ManagedThreadId);
}
});
t.Start();
await t;

The procedure remains unchanged In a flash , Quit immediately .

analysis

First of all, analyze Task.Run() and Task.Factory.StartNew().

We will async Of the tag λ After the expression is passed in as a parameter , The compiler will λ The expression is mapped to Func<Task> perhaps Func<Task<TResult>> entrust , In this example, because there is no return value , So the mapping is Func<Task>.

If we use F12 Investigate Task.Run() and Task.Factory.StartNew() Input parameter is Func<TResult> In the case of the return value type , You will find that the return type of both of them is Task<TResult>. But in the example , You'll find that , The return value is different .Task.Run(async () ...) The return type of is Task, and Task.Factory.StartNew(async () ...) The return type of is Task<Task>.

therefore , We are await Task.Factory.StartNew(async () ...) When , In fact await Task<Task>, As a result, , It's still a Task. In that case , Want to reach and await Task.Run(async () ...) The effect is very simple , Just add one more await, namely await await Task.Factory.StartNew(async () ...). Readers can try it on their own .

The difference between the behavior of these two methods , The reason can be found in the source code :

Task.Run The interior of Unwrap, hold Task<Task> The outer Task Tear it down .UnWrap() There is a way , Can be called directly , namely Task.Factory.StartNew(async () ...).Unwrap(), The result of the call is Task. therefore await await Task.Factory.StartNew(async () ...) And await Task.Factory.StartNew(async () ...).Unwrap() The results are consistent . At this point ,Unwrap() The role of await It does the same thing .

That is to say :await Task.Run(async () ...) == await await Task.Factory.StartNew(async () ...) == await Task.Factory.StartNew(async () ...).Unwrap().

Next, take a look New Task() In the form of . stay code snippet 2 in , Although the call await t, But the code didn't run as expected , But in a flash , Program exit . Actually , Although the parameters passed in are consistent with the previous , however The compiler does not map parameters to Func<Task>, Instead, it maps to Action(), That is, there is no return value .t.Start() Result , Just let that Action() Start execution , And then ,Task completion of enforcement ,await t It will be completed in an instant , There is no result —— because Action() There is no return value . In this code ,Action() Actually, it runs in a background thread , If used on the main thread Thread.Sleep(10000) after , You will find that the console has been outputting content .

If you want to New The way to create Task The example of achieves the same output effect , Just make a small change , As shown below :

code snippet 3

Click to view the code
 var t = new Task<Task>(async () =>
{
while (true)
{
Console.WriteLine("Fuck World! Threads :" + Thread.CurrentThread.ManagedThreadId);
await Task.Delay(2000);
Console.WriteLine(" Threads id:" + Thread.CurrentThread.ManagedThreadId);
}
}); t.Start();
await await t;

take New Task(async ()...) Change it to Nwe Task<Task>(async ()...) That's all right. , such λ expression async ()... It will be mapped to Func<Task>, It meets our asynchronous needs .

Reference resources

Task Source code :https://github.com/dotnet/runtime/blob/main/src/libraries/System.Private.CoreLib/src/System/Threading/Tasks/Task.cs

Task.Run(), Task.Factory.StartNew() and New Task() More related articles on behavior inconsistency analysis

  1. C# Task,new Task().Start(),Task.Run();TTask.Factory.StartNew

    1. Task task = new Task(() => { MultiplyMethod(a, b); }); task.Start(); 2. Task task = Task.Run(( ...

  2. Task.Run Vs Task.Factory.StartNew

    stay .Net 4 in ,Task.Factory.StartNew It's about starting a new Task The preferred method . It has a lot of overload methods , So that it can be very flexible in specific use , By setting optional parameters , Can pass any state , Cancel the mission and continue , even to the extent that ...

  3. Task.Run Vs Task.Factory.StartNew z

    stay .Net 4 in ,Task.Factory.StartNew It's about starting a new Task The preferred method . It has a lot of overload methods , So that it can be very flexible in specific use , By setting optional parameters , Can pass any state , Cancel the mission and continue , even to the extent that ...

  4. Task.Run And Task.Factory.StartNew The difference between

    Task It's a unit of work that may have delays , The goal is to generate a result value , Or produce the desired effect . The difference between a task and a thread is : The task represents the work to be performed , And the thread represents the worker who does the job . stay .Net 4 in ,Task.Factory.Star ...

  5. C# Task.Run and Task.Factory.StartNew difference

    Task.Run Is in dotnet framework 4.5 Can be used later , however Task.Factory.StartNew You can use more than Task.Run More parameters , You can do more customization . You can recognize ...

  6. Task.Run Vs Task.Factory.StartNew 【 Collection 】

    stay .Net 4 in ,Task.Factory.StartNew It's about starting a new Task The preferred method . It has a lot of overload methods , So that it can be very flexible in specific use , By setting optional parameters , Can pass any state , Cancel the mission and continue , even to the extent that ...

  7. 【.NET】- Task.Run and Task.Factory.StartNew difference

    Task.Run  Is in dotnet framework 4.5 Can be used later , Task.Factory.StartNew  You can use more than  Task.Run  More parameters , You can do more customization . It can be said that ...

  8. Task.Run and Task.Factory.StartNew

    stay .Net 4 in ,Task.Factory.StartNew It's about starting a new Task The preferred method . It has a lot of overload methods , So that it can be very flexible in specific use , By setting optional parameters , Can pass any state , Cancel the mission and continue , even to the extent that ...

  9. Task.Run and Task.Factory.StartNew difference

    Task.Run  Is in dotnet framework 4.5 Can be used later , Task.Factory.StartNew  You can use more than  Task.Run  More parameters , You can do more customization . It can be said that ...

  10. task.factory.startnew()

    1. entrust : public delegate int Math(int param1,int param2); Define delegate type Public int Add(int param1,int param2)// ...

Random recommendation

  1. Big bear, big talk NodeJS And ------Connect Middleware module ( Season one )

    One , Opening analysis As of today ,NodeJS There are nearly ten articles in this series , Let's review : (1), Big bear, big talk NodeJS The beginning ------Why NodeJS( take Javascript Go to the end ) (2), Big ...

  2. myeclipse The console prints null pointers , Paste the console sql To plsql With result set , exception handling

    Credit company framework , Not familiar with . After completing the click login , Writing dynamic pages is a problem , The problem of :myeclipse The console prints null pointers , Paste the console sql To plsql With result set , exception handling . Finally, the great God showed it , Return in the method rewritten by the interface implementation ...

  3. Sign and issue for free ssl certificate

    Self made ssl certificate : Sign and issue for free ssl certificate , by nginx Generate self signature ssl certificate Here under Linux How the system passes openssl Command to generate certificate . First, execute the following command to generate a keyopenssl genrsa ...

  4. protocolbuffe

    protocolbuffer( hereinafter referred to as PB) yes google A data exchange format of , It is independent of language , Platform independent .google Provides the implementation of multiple languages :java.c#.c++.go and  python, Every kind of reality ...

  5. 2000 Asia shanghai Dance Dance Revolution

    Ideas :dp[i][x][y] It means the first one i Of the sequences , The right foot is x Location , Left foot in y When in position , Its minimum cost . that dp[i][x][y]=min(dp[i-1][a[i]][y]+cost[a[i]][x],dp[i-1 ...

  6. BZOJ 1613: [Usaco2007 Jan]Running Bessie's morning exercise program

    subject 1613: [Usaco2007 Jan]Running Bessie's morning exercise program Time Limit: 5 Sec  Memory Limit: 64 MB Description Cows plan to exercise to ...

  7. C# Value passing and by reference

    Knowledge point : Value type and reference type   Value type ,, According to the         For reference types , What is stored in the stack is the address of the object in the heap Value passing and reference passing For value passing , What is passed is the data stored in the stack         For reference passing . What is passed is stack book ...

  8. Simple DNA Sequence assembly ( Acyclic subgraph )

    The fourth bullet of bioinformatics principle operation :DNA Sequence assembly ( Acyclic subgraph ) principle : Bioinformatics ( Xiao Sun ) General idea : 1. This algorithm is difficult to understand the details , It is suggested to read the relevant chapters of sun Xiao's bioinformatics . 2. The algorithm requires that all sequences cover the whole target D ...

  9. take Windows Server 2016 Build a workstation (20161030 to update )

    take Windows Server 2016 Build a workstation (20161030 to update ) One . Foundation setup 1.1. Turn off the pop-up window :   「 The start menu 」 - 「 Server Manager 」 - 「 instrument panel 」( or Win + R or CMD ...

  10. The simplest ever Docker Introductory tutorial

    install Ubuntu Docker install CentOS Docker install Windows Docker install MacOS Docker install My computer here is mac, use brew install , Remember to replace it after installation ...