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

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

问题描述

我知道如何创建异步方法,但说我有一个方法可以完成大量工作然后返回一个布尔值?

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;
}

我希望能够使其异步.

推荐答案

有几种方法可以做到这一点...最简单的是让异步方法也做后续操作.另一种流行的方法是传入回调,即

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);
}

另一种方法是在异步操作完成时引发事件(结果在 event-args 数据中).

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

另外,如果你使用的是 TPL,你可以使用 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天全站免登陆