Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Write an Async method that will await a bool

Tags:

I would like to write a method that will await for a variable to be set to true.

Here is the psudo code.

bool IsSomethingLoading = false SomeData TheData;  public async Task<SomeData> GetTheData() {    await IsSomethingLoading == true;    return TheData; } 

TheData will be set by a Prism Event along with the IsSomethingLoading variable.

I have a call to the GetTheData method, but I would like it to run async (right now it just returns null if the data is not ready. (That leads to other problems.)

Is there a way to do this?

like image 605
Vaccano Avatar asked Feb 27 '13 21:02

Vaccano


1 Answers

In many situations like this what you need is a TaskCompletionSource.

You likely have a method that is able to generate the data at some point in time, but it doesn't use a task to do it. Perhaps there is a method that takes a callback which provides the result, or an event that is fired to indicate that there is a result, or simply code using a Thread or ThreadPool that you are not inclined to re-factor into using Task.Run.

public Task<SomeData> GetTheData() {     TaskCompletionSource<SomeData> tcs = new TaskCompletionSource<SomeData>();     SomeObject worker = new SomeObject();     worker.WorkCompleted += result => tcs.SetResult(result);     worker.DoWork();     return tcs.Task; } 

While you may need/want to provide the TaskCompletionSource to the worker, or some other class, or in some other way expose it to a broader scope, I've found it's often not needed, even though it's a very powerful option when it's appropriate.

It's also possible that you can use Task.FromAsync to create a task based on an asynchronous operation and then either return that task directly, or await it in your code.

like image 127
Servy Avatar answered Nov 14 '22 11:11

Servy