Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

winforms - Run code on UI thread without control object present

I currently trying to write a component where some parts of it should run on the UI thread (explanation would be to long). So the easiest way would be to pass a control to it, and use InvokeRequired/Invoke on it. But I don't think that it is a good design to pass a control reference to a "data/background"-component, so I'm searching for a way to run code on the UI thread without the need of having a control available. Something like Application.Dispatcher.Invoke in WPF...

any ideas, thx Martin

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

There's a better, more abstract way to do this that works on both WinForms and WPF:

System.Threading.SynchronizationContext.Current.Post(theMethod, state);

This works because WindowsForms installs a WindowsFormsSynchronizationContext object as the current sync context. WPF does something similar, installing it's own specialized synchronization context (DispatcherSynchronizationContext).

.Post corresponds to control.BeginInvoke, and .Send corresponds to control.Invoke.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...