在C#中调用BeginInvoke/Invoke时如何获取返回值 [英] How to get return value when BeginInvoke/Invoke is called in C#

查看:1845
本文介绍了在C#中调用BeginInvoke/Invoke时如何获取返回值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个应该是线程安全的小方法.一切正常,直到我希望它具有返回值而不是void.调用BeginInvoke时如何获取返回值?

I've this little method which is supposed to be thread safe. Everything works till i want it to have return value instead of void. How do i get the return value when BeginInvoke is called?

public static string readControlText(Control varControl) {
        if (varControl.InvokeRequired) {
            varControl.BeginInvoke(new MethodInvoker(() => readControlText(varControl)));
        } else {
            string varText = varControl.Text;
             return varText;
        }

    }

在这种情况下,我想拥有BeginInvoke并不是必需的,因为在线程可以继续之前,我需要GUI的值.因此,使用Invoke也很好.在下面的示例中,根本不知道如何使用它来返回值.

I guess having BeginInvoke is not nessecary in this case as i need value from GUI before the thread can continue. So using Invoke is good as well. Just no clue how to use it in following example to return value.

private delegate string ControlTextRead(Control varControl);
    public static string readControlText(Control varControl) {
        if (varControl.InvokeRequired) {
            varControl.Invoke(new ControlTextRead(readControlText), new object[] {varControl});
        } else {
            string varText = varControl.Text;
             return varText;
        }

    }

但也不确定如何使用该代码获取价值;)

But not sure how to get value using that code either ;)

推荐答案

您必须调用Invoke(),以便可以等待函数返回并获取其返回值.您还需要另一种委托类型.这应该起作用:

You have to Invoke() so you can wait for the function to return and obtain its return value. You'll also need another delegate type. This ought to work:

public static string readControlText(Control varControl) {
  if (varControl.InvokeRequired) {
    return (string)varControl.Invoke(
      new Func<String>(() => readControlText(varControl))
    );
  }
  else {
    string varText = varControl.Text;
    return varText;
  }
}

这篇关于在C#中调用BeginInvoke/Invoke时如何获取返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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