我应该使用或调用到的SynchronizationContext从另一个线程更新表单控件? [英] Should I use Invoke or SynchronizationContext to update form controls from another thread?

查看:240
本文介绍了我应该使用或调用到的SynchronizationContext从另一个线程更新表单控件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

试图环绕其他线程更新UI控件我的头。

Trying to wrap my head around updating UI controls from other threads.

目前使用的BeginInvoke和诚实它的工作不错,但我不断听到有关如何使用的SynchronizationContext作为很好地做同样的事情。

Currently using BeginInvoke and honestly it's working fine but I keep hearing about how you can use SynchronizationContext as well to do the same thing.

这是首选?

此外,它是不好的做法,更新从一个线程的用户界面?它会更好引发一个事件,并有主要方式处理它,而不是或有其他最好的方式做到这一点呢?

Also, is it bad practice to update the UI from a thread? Would it be better to raise an event and have the main form handle it instead or are there other preferable ways to do that as well?

对不起,我有些主观的问题,但还有在线程的世界这么多的选择,我努力要抓住他们的分歧,每个人都适用,具有写可读和可扩展的代码对未来的最佳实践一起。

Sorry for the somewhat subjective question but there are so many options in the world of threading and I'm trying to grasp their differences and where each of them are applicable, along with best practices for writing readable and extendable code for the future.

编辑:另外现在我看到有在 TaskScheduler.FromCurrentSynchronizationContext 路线以及..这么多的选择X_X

Also now I see there is the TaskScheduler.FromCurrentSynchronizationContext route as well.. So many choices x_x

推荐答案

我喜欢的SynchronizationContext Control.Invoke Control.Invoke 的危险是,有一个终身的问题与拥有控制。如果当您试图调用其上的控制置于那么它损害的通话成功的能力。发生这种情况时,对话框关闭,观点转向,等等...

I prefer SynchronizationContext over Control.Invoke. The danger of Control.Invoke is that there is a lifetime issue with the owning Control. If the Control is disposed while you are trying to Invoke on it then it compromises the ability of the call to succeed. This happens when dialogs are closed, views shifted, etc ...

SynchronizationContext.Current 虽然一般的生活,只要因为它的线程的关联。它有一个有限的寿命,因此最终同样的问题,但它比控制更可预见的一点。

SynchronizationContext.Current though generally lives as long as the thread it's associated with. It does have a finite lifetime and hence ultimately the same problems but it's a bit more predictable than a Control.

这篇关于我应该使用或调用到的SynchronizationContext从另一个线程更新表单控件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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