开发者

GUI with socket in another thread

I want to create a WinForm application that must draw data com开发者_如何学运维ing from a socket.

I want to put the code reading from a socket in a separate thread and I am aware of the InvokeRequired/BeginInvoked pattern.

Which type of C# thread is the most suited for my purpose considering the WinForm scenario? Is it enough a common System.Threading.Thread entirely dedicated to reading data from socket or other types like BackgroundWorker? Or should I consider something else?


Thread workerThread = new Thread();
// do threadstart parameters or whatever
workerThread.IsBackground = true;
workerThread.Start();

This should be sufficient...you can even set it's priority if that is a concern.

I don't particularly care for BackgroundWorker. Even though the events are helpful, I don't need the help. I find it limiting because I use a lot of asynchronous methods (Action/Func).

As MSDN states the process with Background Worker:

To set up for a background operation, add an event handler for the DoWork event. Call your time-consuming operation in this event handler. To start the operation, call RunWorkerAsync. To receive notifications of progress updates, handle the ProgressChanged event. To receive a notification when the operation is completed, handle the RunWorkerCompleted event.

It just seems a lot simpler to use System.Threading.Thread.


You could use the APM pattern, ie

 mySocket.BeginReceive(..., myCallBack);

But it is not my favorite pattern. I would use the ThreadPool, possibly through a BackgroundWorker.


Is this thread running for a long time? If you need it to run for a long time, and if you don't need to directly interact with a GUI (maybe cache data to a buffer), then I would use System.Threading.Thread. I have been using BackgroundWorker and found that, while it allows you to update the GUI via its event, it uses the .NET threadpool. The threadpool has a finite amount of threads available, so if you need to use Windows Workflow or lots of delegates via BeginInvoke, you could hurt application performance by tying up too many threadpool threads.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜