我是C# Task和线程的新手.
I am new to C# Task and threading.
我有如下代码:-
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?
能否请您指出如何从Task更新UI?我没有使用async/await,因为UpdateSales是第三方库中的事件处理程序.
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.
推荐答案假设在UI线程上调用了UpdateSales,则更干净的解决方案是:
Assuming that UpdateSales is called on the UI thread, a cleaner solution would be this:
public async void UpdateSales() { var collection = await Task.Run(() => { // Some code Create Collection ... // Some code with business logic .. return currentCollection; }); saleDataGrid.ItemsSource = collection; saleDataGrid.Items.Refresh(); }正如我在博客中所述, await将自动恢复在捕获的上下文中(在本例中为UI上下文).我更喜欢直接使用await的隐式上下文,而不是直接使用Dispatcher:代码更短,更可移植.
As I describe on my blog, the await will automatically resume on a captured context (in this case, the UI context). I much prefer using the implicit context of await rather than Dispatcher directly: the code is shorter and more portable.
更多推荐
C#在任务中更新UI
发布评论