Dispatcher.Dispatch on the UI thread

前端 未结 2 997
死守一世寂寞
死守一世寂寞 2020-12-10 21:05

I have the doubt regarding when to use the Dispatcher.Invoke to update something on UI from different Thread.

Here\'s my code...

public Window4()
            


        
2条回答
  •  难免孤独
    2020-12-10 21:17

    Your test isn't valid as it isn't actually updating your UI. If you want proof, add this sleep call:

    public void Test()
    {
        Thread.Sleep(10000);
        listOfString.Add("abc");
        listOfString.Add("abc");
        listOfString.Add("abc");
    }
    

    You'll find that your UI appears and the list is empty. 10 seconds, 30 seconds, 3 months later, the list won't contain your strings.

    Instead your test is demonstrating a race condition - your Test() method is completing fast enough that the strings are added to the list before the UI appears on screen and reads the list.

    To fix it, change your collection to an ObservableCollection. But then you'll encounter the next problem - you can't update an ObservableCollection on a background thread. So that's where the Dispatcher comes in.

提交回复
热议问题