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

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

问题描述

我有一个程序可以通过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()' s委托函数访问返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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