Update progress bar in MainWindow from a different Thread

前端 未结 2 1625
挽巷
挽巷 2021-01-01 08:17

I know this question has been asked several times an I spent all day trying to understand other answers, but since I am very new to C# and WPF nothing helped me so far. I wi

2条回答
  •  长情又很酷
    2021-01-01 08:40

    You can use Dispatcher.BeginInvoke() to push UI changes on the UI thread rather than worker thread. Most important thing - you need to access Dispatcher which is associated with UI thread not a worker thread you are creating manually. So I would suggest cache Dispatcher.Current and then use in a worker thread, you can do this via ParametersClass or just declaring a dispatchr field on a class level.

    public partial class MainWindow
    {
        private Dispatcher uiDispatcher;
    
        public MainWindow()
        {
            InitializeComponents();
    
            // cache and then use in worker thread method
            this.uiDispatcher = uiDispatcher;
        }
    
        public void MyLongCalculations(object myvalues)
        {
            ParameterObject values = (ParameterObject)myvalues;
            this.uiDispatcher.BeginInvoke(/*a calculations delegate*/);
        }
    }
    

    Also if you need to pass a UI dispatcher in some service/class (like ParametersClass) I would suggest take a look at this nice SO post which show how you can abstract it by an interfaces with ability to push UI changes synchronously/asynchronously so it would be up to a caller (basically use Invoke() or BeginInvoke() to queue a delegate in the UI messages pipeline).

提交回复
热议问题