开发者

Writing a Multi-threaded C# application

I need to write an application in c# that keeps track of multiple tasks, each being implemented as a class instance running on its own thread. A user interface will be used to display the status of each task instance depending on which task I select from tree view which will display the list of tasks.

An idea I have is to create some other class, called PropertyClass which will have an开发者_运维知识库 instance of the TaskClass and some properties relating to this TaskClass instance. Then whenever the TaskClass instance changes its state the related property in the PropertyClass instance will get updated and then the UI will be updated with these property values from the PropertyClass when the task is selected from the Tree View list.

There will probably be hundreds of these tasks running which will be communicating with a service on a remote machine.

How else can I go about coding this solution in an efficient way?


Read this document from the MSDN on the Task Parallel Library first.


I have a few suggestions.

First, you need a way to make sure you don't end up with threads blocking your app from closing. One sure fire way to do this is to make sure all your threads are background threads. That can be a little problematic if you have to make sure a thread's work is done before it is joined or aborted.

Second, you could look at using the ThreadPool class which should make creating and using threads more efficient. The thread pool is there to help you manage your threads.

Third, you will need a method of synchronizing your data access from the GUI to data in the other threads. In WPF you use the Dispatcher and in WinForms you'll use Invoke.

Forth, the BackgroundWorker class can help with all of these if it'll fit in the model of your application.

Fifth, events and delegates can be BeginInvoked which essentially puts them on another thread. It's kind of implicit multi-threading and can be useful.

Sixth, and I've not yet had the chance to use this, .Net 4 has the Parallel Task Library that may be of use to you.

Seventh, safe shared data access and synchronization can be accomplished using lock and/or Monitor.

Hope this helps.

-Nate


If each TaskClass instance corresponds to a node on the tree view, you can store the TaskClass instance in the tree view item's Tag property. Or you could create a dictionary of TaskClasses, keyed by a unique identifier such as a GUID, and store the identifier in the Tag property.

In either case, use a callback method to signal that a TaskClass instance has an update.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜