如何使异步方法返回一个值? [英] How to make an Asynchronous Method return a value?

查看:194
本文介绍了如何使异步方法返回一个值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道如何使异步方法,但说我有,做了很多工作,然后返回一个布尔值的方法?

I know how to make Async methods but say I have a method that does a lot of work then returns a boolean value?

如何在回调返回布尔值?

How do I return the boolean value on the callback?

澄清

public bool Foo(){
    Thread.Sleep(100000); // Do work
    return true;
}

我希望能够使这个异步

I want to be able to make this asynchronous.

推荐答案

有这样做的几种方法......最简单的就是有异步方法也做了后续的操作。另一种流行的做法是在回调,即通过。

There are a few ways of doing that... the simplest is to have the async method also do the follow-on operation. Another popular approach is to pass in a callback, i.e.

void RunFooAsync(..., Action<bool> callback) {
     // do some stuff
     bool result = ...

     if(callback != null) callback(result);
}

另一种方法是提高一个事件(其结果在事件ARGS数据)时,异步操作完成

Another approach would be to raise an event (with the result in the event-args data) when the async operation is complete.

此外,如果您使用的是第三方物流,可以使用 ContinueWith

Also, if you are using the TPL, you can use ContinueWith:

Task<bool> outerTask = ...;
outerTask.ContinueWith(task =>
{
    bool result = task.Result;
    // do something with that
});

这篇关于如何使异步方法返回一个值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆