简体   繁体   English

如果我通过ParameterizedThreadStart将对象传递给线程,我以后可以访问它吗?

[英]If I pass an object to a thread via ParameterizedThreadStart, can I access it later?

If I start a thread in the following manner 如果我以以下方式启动线程

Thread newThread = new Thread(new ParameterizedThreadStart(MyThreadMethod));
Object myObject = new Object();
newThread.Start(myObject);

Can I find out what has it done to myObject after it has finished the task? 完成任务后,我能否找出对myObject做了什么?

// at some point later
if(newThread.ThreadState == ThreadState.Stopped)
{
//access my object? how?
}

You handed it the object. 您将对象交给了它。 So just store the object that you hand alongside the thread that you start. 因此,只需将您传递的对象存储在启动的线程旁边。 Be very careful about what you do with it though, or you may run into interesting threading issues. 不过,请务必谨慎处理,否则可能会遇到有趣的线程问题。

Sure. 当然。 The stopping of the Thread in no way destroys the object passed off to it. 线程的停止绝不会破坏传递给它的对象。 As long as there is still a reference to the object, and it's not been disposed, it's still valid to use. 只要仍然有对该对象的引用,并且未对其进行处理,则使用该对象仍然有效。

However there is no inherent way to get the value passed to the Thread::Start method back. 但是,没有固有的方法来获取传递回Thread :: Start方法的值。 Instead you'll have to keep a reference to it, probably from where you started the thread. 取而代之的是,您可能必须从启动线程的位置开始对其进行引用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM