views:

50

answers:

3

I have a form and several external classes (serial port, file access) that are instantiated by the form.

1) What's the simplest way to run an instance of an external class in its own thread?

2) Is the instance's thread automatically terminated when the form closes?

+1  A: 

If it's just a couple of lines of code you want to call asynchronously, probably the best way is ThreadPool.QueueUserWorkItem. See: http://stackoverflow.com/questions/532791/whats-the-difference-between-queueuserworkitem-and-begininvoke-for-performi

Shlomo
I don't think that's what I want, and the classes can be as big as they need to be. I'm looking for a simple way to start asynchronous instances from a parent form, and terminate them when the form closes.
OIO
A: 

See if you are working with managed Environment, when an object is instantiated it will automatically dispose off if it is out of scope. The Disposal is actually taken care of by Garbage collection.

If you are using UnManaged objects, its your responsibility to close resources before making the object out of scope.

Garbage collection periodically turns on and start collecting all the objects that are out of scope. If you need to work on large objects, you can try using WeakReference class which will hold the object but also expose it for Garbage collection.

Read about WeakReference and garbage collection from here: http://www.abhisheksur.com/2010/07/garbage-collection-algorithm-with-use.html

I hope this would help you.

abhishek
Not sure if this applies to the second question, automatically terminating threads started from a form.
OIO
No matter in which thread you are, Garbage Collection works on all threads or irrespective of Threads.When your form closes, you can explicitly set the instance variables to null to make them available to Garbage collection.
abhishek
+2  A: 

1) What's the simplest way to run an instance of an external class in its own thread?

Instances of classes do not "run". Methods do.

As such, you may want to look into the APM pattern and the BackgroundWorker class.

2) Is the instance's thread automatically terminated when the form closes?

It depends on how the threads were started. A thread can be a background thread or a foreground thread - the latter prevents the application from terminating.

andras
I'm checking the Event-based Asynchronous Pattern and the BackgroundWorker class.
OIO