简体   繁体   中英

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?

// 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. Instead you'll have to keep a reference to it, probably from where you started the thread.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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