C#在任务中更新UI

编程入门 行业动态 更新时间:2024-10-25 10:23:18
本文介绍了C#在任务中更新UI的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我是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

本文发布于:2023-11-12 01:34:03,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1580135.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:UI

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!