WPF/C# 中这种线程方式效率低下吗?
这样做是否比设置后台工作线程效率低?因为它运行良好并且看起来更干净。在循环中,我调用 BeginInvoke 3x - 将行添加到主窗口数据网格,并更新进度条和消息。
public MyConstructor()
{
InitializeComponent();
ThreadStart start = delegate()
{
for (...)
{
...
MyWindow.Dispatcher.BeginInvoke(DispatcherPriority.Normal,
new Action(delegate()
{
// Do something on the MyWindow thread.
}
));
...
}
// Intensive loop now done and we close this processing window.
this.Dispatcher.BeginInvoke(DispatcherPriority.Normal,
new Action(delegate()
{
this.Close();
}
));
}; // ThreadStart
new Thread(start).Start();
}
Is doing this less efficient than setting up a background worker thread? Because it is working well and seems cleaner. In the loop I am calling BeginInvoke 3x - to add rows to main window datagrid, and to update the progress bar and message.
public MyConstructor()
{
InitializeComponent();
ThreadStart start = delegate()
{
for (...)
{
...
MyWindow.Dispatcher.BeginInvoke(DispatcherPriority.Normal,
new Action(delegate()
{
// Do something on the MyWindow thread.
}
));
...
}
// Intensive loop now done and we close this processing window.
this.Dispatcher.BeginInvoke(DispatcherPriority.Normal,
new Action(delegate()
{
this.Close();
}
));
}; // ThreadStart
new Thread(start).Start();
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
对我来说它看起来不太干净......
但除此之外,我认为没有理由不这样做。但我也没有看到不使用BackgroundWorker的原因:
它对我来说看起来更干净,因为你在线程中完成的实际工作和UI更新之间有一点分离......
It doesn't exactly look clean to me...
But other than that, I see no reason for not doing it. But I also do not see a reason, for not using the BackgroundWorker:
It looks cleaner to me, because you have a little separation of the real work that is done in the thread and the UI updating...
没关系,但有几点:
您实际上并没有非常清楚地限定“高效”,但BackgroundWorker通常是做这类事情的更好方法 - 如果没有别的办法,它将使用池线程,这比池线程便宜得多手动创建的线程。
It's OK-ish, but a few points:
You don't really qualify 'efficient' very clearly, but BackgroundWorker is generally a better way of doing this sort of thing - if nothing else, it will use a pool thread, which is much cheaper than a manually created thread.