Update UI from multiple worker threads (.NET)

前端 未结 6 1373
清酒与你
清酒与你 2020-12-15 13:13

I have a pet project that I\'m working on that has multiple worker threads. Outputting everything to the console is getting hard to follow, so I want to develop a UI that wi

6条回答
  •  醉梦人生
    2020-12-15 13:48

    If you're creating your own threads (non BackgroundWorker or ThreadPool threads) you can pass a callback method from your main thread that's called from the worker thread. This also lets you pass arguments to the callback and even return a value (such as a go/no-go flag). In your callback you update the UI through the target control's Dispatcher:

    public void UpdateUI(object arg)
    {
        controlToUpdate.Dispatcher.BeginInvoke(
            System.Windows.Threading.DispatcherPriority.Normal
            , new System.Windows.Threading.DispatcherOperationCallback(delegate
            {
                controToUpdate.property = arg;
                return null;
            }), null);
        }
    } 
    

提交回复
热议问题