从Thread.Start()的委托功能的访问返回值 [英] Access return value from Thread.Start()'s delegate function

查看:1184
本文介绍了从Thread.Start()的委托功能的访问返回值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经得到了通过Thread.Start执行方法的程序。该方法,我想获得访问返回值。有没有办法做到这一点?这里有一个采样...

I've got a program that executes a method through a Thread.Start. The method has a return value that I'd like to get access to. Is there a way to do this? Here's a sampling...

var someValue = "";
Thread t = new Thread(delegate() { someValue = someObj.methodCall(); });

t.Start();

while (t.isAlive) Thread.Sleep(1000);

// Check the value of someValue



所以一旦while循环结束,在someValue中应该设置 - 但是因为它在另一个线程中执行它不会设置。有没有一种简单的方法来访问它?

So once the while loop ends, the someValue should be set - but because it's executed in another thread it doesn't get set. Is there a simple way to get access to it?

推荐答案

当主叫用户和螺纹方法份额的变量,你已经有了访问它 - 一旦线程完成,您只需检查 someValue中

When the caller and the threaded method share a variable, you already have access to it - once the thread has completed, you just check someValue.

当然,你必须知道当螺纹方法完成此是有用的。在底部,有两种方法可以做到这一点:

Of course, you have to know when the threaded method is complete for this to be useful. At the bottom, there are two ways to do this:


  • 发送回叫入螺纹方法时,它的,它可以执行完了。您可以将您的回调方法 someValue中。您可以使用此方法,如果你的回调执行时不小心。

  • Send a callback into the threaded method that it can execute when it's finished. You can pass your callback method someValue. You can use this technique if you don't care when the callback executes.

使用的 的WaitHandle 某种(或的 的Thread.join )。这些告诉你,当资源就绪或事件已完成。如果你想别的启动一个线程,做一些这种技术是有用的,的然后的等待线程,然后再继续完成。 (换句话说,它如果要同步备份与线程是非常有用的,只是不是现在。)

Use a WaitHandle of some kind (or Thread.Join). These tell you when a resource is ready or an event has completed. This technique is useful if you want to start a thread, do something else, then wait until the thread completes before proceeding. (In other words, it's useful if you want to sync back up with the thread, just not right away.)

这篇关于从Thread.Start()的委托功能的访问返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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