问题
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:
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).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