Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

wpf - C# Update UI In Task

I am new to C# Task and threading.

I have a code like below:-

public void UpdateSales(object sender, EventArgs args)
{
    Task.Run(() =>
    {
    // Some code Create Collection ...
    // Some code with business logic  ..


    // Below code is to update UI
    // is it safe to update UI like below 

       saleDataGrid.Dispatcher.Invoke((Action) (() =>
                                {

                                    saleDataGrid.ItemsSource = currentCollection;
                                    saleDataGrid.Items.Refresh();
                                })); 

    });
}

I am not sure if this code is correct or not. I am think in any case deadlock can occur?

Can you please point how can i update UI from Task? i am not using async/await because UpdateSales is event handler from third party library.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

As you know, Task.Run will execute on a threadpool thread.

You can then use a ContinueWith which will run at the completion of that task - and if you choose one of the overrides that allows you to specify a TaskScheduler then you can use TaskScheduler.FromCurrentSynchronizationContext() which will use the synchronization context that you entered the method on - if that is a UI thread (for example you are in an event handler for a UI event) then the synchronization context will be that of the UI thread.

So your code will look something like this:

Task.Run(() => {
                   ...code to create collection etc...
               }
        )
        .ContinueWith(() => {
                                saleDataGrid.ItemsSource = currentCollection;
                            }
                      , TaskScheduler.FromCurrentSynchronizationContext()
                     );

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...