开发者

New Thread for Instance of a Class (C#)

I have a form and several exte开发者_C百科rnal 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) 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.


If it's just a couple of lines of code you want to call asynchronously, probably the best way is ThreadPool.QueueUserWorkItem. See: What's the difference between QueueUserWorkItem() and BeginInvoke(), for performing an asynchronous activity with no return types needed


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜