这是线程/后台工作设计为一个C#WPF应用程序是否正常? [英] Is this thread/background worker design for a C# WPF application OK?

查看:109
本文介绍了这是线程/后台工作设计为一个C#WPF应用程序是否正常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

作为新来使用线程等在用户界面的,可我问的是下面这个简单的设计,似乎确定。请参阅在这里链接关系图图片

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

在特定的:

一)使用的BackgroundWorker和放大器; BackgroundWorker的ProgressChanged有一个单独的线程聚合器的工作。所以,我需要一个自定义类/类型有所有我需要从聚合线程传递回UI线程我假设数据。

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.

二)创建聚合在一个单独的线程,以确保SharpPCap / WinPcap的回调方法是在不同的线程。因此,这捕获管理器线程分组结果写入到一个共享的缓存。我假设在这里,如果code可以看到缓存变量,它们都可以访问它,不论他们是在跑?哪个线程

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?

感谢

推荐答案

我有几个建议:

  1. 我不建议使用一个BackgroundWorker和ProgressChanged这一点。既然你想民意调查和汇总每隔1秒,我建议只使用一个定时器(可能是DispatcherTimer)。您可以使用 Dispatcher.BeginInvoke 当元帅的电话返回到UI线程,如果你有这个运行在一个单独的线程(你也可以使用一个UI线程基于定时器,如果你想)。

  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).

我会建议使用 ConcurrentQueue&LT ; T> 持有,而不是一个列表的分组数据。这将$ P $与需要在你的名单锁定pvent你。如果你一定要坚持.NET&LT版本;某些对象,但你需要同步到它访问(锁; 4,您可以使用名单,其中,T&GT保护的读/写操作中的列表)。这两个线程就可以使用相同的集合,只要它是线程安全的或正确同步。

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.

这篇关于这是线程/后台工作设计为一个C#WPF应用程序是否正常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆