Is this thread/background worker design for a C# WPF application OK?

天涯浪子 提交于 2019-12-06 14:28:02

问题


Being new to using threads etc in UI's, can I ask is the following simple design seem OK. Refer to diagram image at link here

In particular:

a) use of backgroundworker & backgroundworker ProgressChanged to have the aggregator work on a separate thread. So I would need a custom class/type that had all the data I'd need to pass back from the aggregator thread to the UI thread I assume.

b) create a separate thread within the aggregator to ensure that the SharpPCap/WinPCap callback method is in a different thread. So this Capture Manager thread writes packet results to a shared Buffer. I'm assuming here that if the code can see the buffer variable that they can both access it, irrespective of which thread they're running in?

thanks


回答1:


I have a couple suggestions:

  1. I wouldn't recommend using a BackgroundWorker and ProgressChanged for this. Given that you want to "poll and aggregate" every 1 second, I'd recommend just using a Timer (probably a DispatcherTimer). You can use Dispatcher.BeginInvoke to marshal the calls back onto the UI thread, if you have this run in a separate thread (you can also use a UI-thread based timer, if you want).

  2. I'd recommend using a ConcurrentQueue<T> to hold your packet data, instead of a list. This will prevent you from needing locking around your list. If you must stick to versions of .NET <4, you can use a List<T>, but you'll need to synchronize access to it (lock on some object to protect read/write operations in the list). Both threads will be able to use the same collection, provided it's thread safe or synchronized correctly.



来源:https://stackoverflow.com/questions/3295560/is-this-thread-background-worker-design-for-a-c-sharp-wpf-application-ok

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!