returning a variable from a worker thread

P

Pesso

I have a worker thread, which returns a value (a System.Xml.XmlDocument
object) to the main WinForm thread. I tried the below, but I'm not sure if
it's done correctly.

public class Form1: System.Windows.Forms.Form
{
// ...
System.Xml.XmlDocument _xmldoc;
// ...
void Func1()
{
Thread workerthread = new Thread( new ThreadStart( Func2 ));
workerthread.Start();
}
void Func2()
{
SomeLib lib = new SomeLib(); // instantiate an object
_xmldoc = lib.LengthyOperation(); // Can I assign a return value from a
thread operation to a private data member like this without any
synchronization?
}
 
B

beau

Hi,

Yes, you can technically do that, but I'm guessing that you eventually
want the contents of the xmldoc to be displayed by the ui or something
like that. To do this correctly, you should make the callback to the
ui via the BeginInvoke/Invoke methods.

You might also want to look at the BackgroundWorker component in .NET
2.0. If you're using 1.1/1.0, there's an implementation on
codeproject. It makes doing these background tasks on the ui simple
and clean.

-beau
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top