Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
506 views
in Technique[技术] by (71.8m points)

c# - Should I use Invoke or SynchronizationContext to update form controls from another thread?

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

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.

Which is preferred?

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.

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...