简体   繁体   中英

await task inside another task

I'm working on a C# console application that will be responsible for running an array of tasks. The basic structure for that is as follows:

var tasks = workItems.Select(x => Task.Factory.StartNew(() =>
{
    DoSomeWork(x);
})).ToArray();

Task.WaitAll(tasks);

The problem is that DoSomeWork() is an async method which awaits the result of another task, which also needs to await a call to the Facebook API. http://facebooksdk.net/docs/reference/SDK/Facebook.FacebookClient.html#GetTaskAsync(string)

public async void DoSomeWork(WorkItem item)
{
    var results = await GetWorkData();
}

public async Task<List<WorkData>> GetWorkData()
{
    var fbClient = new FacebookClient();
    var task = fbClient.GetTaskAsync("something");
    var fbResults = await task;
};

I thought I would be able to support this notion of nested tasks with the call to Task.WaitAll() but the execution of the parent tasks finishes almost immediately. Putting a Console.ReadLine() at the end of the application to prevent it from early execution shows that the result will indeed come back later from Facebook.

Am I missing something obvious or is there a better way to block for my Task collection that will allow for this kind of scenario?

DoSomeWork needs to not return void . The by not returning a Task the caller has no way of knowing when if finishes.

Additionally, it's already asynchronous, so there is no reason to use StartNew here. Just call DoSomeWork directly, since it should be returning a Task .

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM