0

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?

1 Answer 1

6

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the quick reply that should have been an easy one. Feeling a little rusty over here haha

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.