While testing a few implementation option I have stumbled on some unclear issues regarding TPL. Basically my question is, When calling an async Task returning method, is a Task created? In the following code, what will happen?
public static void Main(string[] args){
Task t = SomeAsyncMethod()
Task.WaitAll(t)
}
private static async Task<IEnumerable<string>> SomeAsyncMethod()
{
//some implementation
}
I assumed a Task should be created in this code but when watching the Parallel Task Debug window no Task was created. Would you please clarify this.
Update: svick gave a good explanation to the above scenario, which created a follow up question. Will the following code create two Task or only one? Is it good practice, when the main goal is to create separate Tasks.:
public static void Main(string[] args) {
Task t = Task.Factory.StartNew(SomeAsyncMethodWrapper());
}
private async void SomeAsyncMethodWrappe(){
ver result = await AsyncMethod();
//do something with the result
}
private static async Task<IEnumerable<string>>(){
//do some work and return a result value
var innerResult = await someLibraryAsyncMethod();
return innerResult;
}
A Task
will be created, otherwise your code couldn't work. But it's a different kind of Task
from the ones that are used for parallel processing, which I assume is what “Parallel Tasks” means.
The difference is that “normal” Task
s are basically wrappers around some synchronous code that usually executes on the ThreadPool
. On the other hand, async Task
s complete when something happens (some information is read from the disk; async
method completes), but they don't directly represent some code and are never associated with a thread.
Method should be like this if you want to see task in Parallel Tasks window.
private static async Task<IEnumerable<string>> SomeAsyncMethod()
{
await Task.Factory.StartNew(() => Thread.Sleep(TimeSpan.FromMinutes(10)));
return new List<string>();
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.