Using SynchronizationContext for sending events back to the UI for WinForms or WPF

后端 未结 2 1339
暖寄归人
暖寄归人 2020-11-27 19:08

I\'m using a SynchronizationContext to marshal events back to the UI thread from my DLL that does a lot of multi-threaded background tasks.

I know the singleton patt

2条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-27 19:43

    Rather than compare to the current one, why not just let it worry about it; then it is simply a case of handling the "no context" case:

    static void RaiseOnUIThread(EventHandler handler, object sender) {
        if (handler != null) {
            SynchronizationContext ctx = SynchronizationContext.Current;
            if (ctx == null) {
                handler(sender, EventArgs.Empty);
            } else {
                ctx.Post(delegate { handler(sender, EventArgs.Empty); }, null);
            }
        }
    }
    

提交回复
热议问题