Public override TaskGetClassA ()
{
The return of Task. The Run (()=& gt; {
ClassA a=new ClassA ();
Return a;
});
}
Public override async TaskGetClassA ()
{
Return await Task. Run (()=& gt; {
ClassA a=new ClassA ();
Return a;
});
}
The two methods in addition to writing the other is the difference between different?
CodePudding user response:
Added async and await the return of the Task of the Result is a new good ClassA object because await such as Task. Run in the content of the execution of theInstead of async and await the return of the Task of the Result is null because at the end of the function performs a Task, the contents have not yet begun to Run in the Run
CodePudding user response:
Asyn asynchronous, with the head don't understand, you can drop to the MSDNCodePudding user response:
This will divide said,Add do not add async, is the same,
but add the async, add do not add await, is not the same,
CodePudding user response:
Async just told that this may be an asynchronous,When the async + await, is asynchronous,
CodePudding user response:
Writing is actually more appropriate fieldpublic override TaskGetClassA ()
{
ClassA a=new ClassA ();
Return Task. FromResult (a);
}
Clear from convenient apt semantic perspective, async is clearly let certain Task< back;> The method is easier to read more apt a "syntactic sugar",
CodePudding user response:
Such as asynchronous methodpublic static async Task t ()
{
Var web=new WebClient ();
Var r=await web. UploadDataTaskAsync (" http://localhost:12341 ", Encoding UTF8. GetBytes (" spsp1234 "));
Var s=Encoding. UTF8. Get string (r);
The Debug. Assert (s.S tartsWith (" path length="));
}
Here because there await to order statement syntax to deduce the concurrent asynchronous operation in reality, less obviously async/await a Task layer encapsulation, clearer,
There may be many await in a big way, even in the loop structure using await, and you give examples of "deliberately" are examples of don't have to await, actually this kind of method does not need to define the Task as a function return value, or can be written as
public override TaskGetClassA ()
{
Await the Tasks. The Yield ();
ClassA a=new ClassA ();
Return a;
}
If you don't have a problem in this manufacturing complex, then actually have trouble,
CodePudding user response:
Less an async above, should be changed to:public override async TaskGetClassA ()
{
Await the Tasks. The Yield ();
ClassA a=new ClassA ();
Return a;
}
In short, you can define a
public override ClassA GetClassA ()the return type of the method, you are now defined as Task
Again, there is no need to use Task. Run (... ) when, in fact use the async/await grammar more relaxed, apt,
CodePudding user response: