问题描述
我想编写一个将await
设置为true的方法.
I would like to write a method that will await
for a variable to be set to true.
这是伪代码.
bool IsSomethingLoading = false
SomeData TheData;
public async Task<SomeData> GetTheData()
{
await IsSomethingLoading == true;
return TheData;
}
TheData
将由棱镜事件以及IsSomethingLoading
变量设置.
TheData
will be set by a Prism Event along with the IsSomethingLoading
variable.
我已经调用了GetTheData
方法,但是我希望它运行异步(现在,如果数据还没有准备好,它只会返回null.(这会导致其他问题.)
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?
推荐答案
在许多情况下,您需要的是TaskCompletionSource
.
In many situations like this what you need is a TaskCompletionSource
.
您可能拥有一种能够在某个时间点生成数据的方法,但是它不使用任务来执行该操作.也许有一种方法可以采用提供结果的回调,或者触发一个事件来表明存在结果,或者只是使用Thread
或ThreadPool
进行编码,而您不希望将其重构为使用Task.Run
.
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;
}
虽然您可能需要/想要将TaskCompletionSource
提供给工作人员或其他类,或者以其他方式将其提供给更广泛的范围,但我发现通常并不需要它,即使它非常适当时提供强大的选择.
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.
还可以使用Task.FromAsync
基于异步操作创建任务,然后直接返回该任务,或者在代码中将其await
退回.
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.
这篇关于写一个异步方法,将等待布尔的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!