WPF 中的调度程序和异步等待 [英] Dispatcher and async await in WPF

查看:35
本文介绍了WPF 中的调度程序和异步等待的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在 WPF/C# 中学习异步编程,但我坚持使用异步编程和使用 Dispatchers.它们是不同的还是它们或将在同一场景中使用?我愿意保持这个问题简短,以免含糊不清,因为我知道我在 WPF 中混淆了一个概念和一个函数,但还不足以在功能上正确使用它.

I am trying to learn asynchronous programming in WPF/C# and I am stuck on asynchronous programming and using Dispatchers. Are they both different or are they or are to be used in the same scenario? I am willing keeping this question short as to not be vague because I understand that I am messing up between a concept and a function in WPF, but not enough to functionally use it correctly.

我在这里问了一个问题后出现了疑问,这是我的问题,有人告诉我使用 Dispatcher 来解决这个问题,并且 WPF 在单线程上运行,您需要使用 BeginInvoke,这是我第一次听到 Dispatcher 的地方,在此之前我只使用 Task.Run 这三个关键字来使用 async 和 await.

My doubt arises after I asked a question here, This is my question, I was told to use Dispatcher for this problem and that WPF runs on a single thread and you need to use BeginInvoke, here was where I first heard Dispatcher and before that I just user async and await with Task.Run these 3 keywords only.

但是这篇文章是异步编程带有 WPF 的 C#.

我需要做的就是将几页加载到 Grid 中,这发生在应用程序的开头(我认为这部分处理的是 DispatcherUI 的一部分),然后 CRUD 到数据库.

All I need to do is load a few pages into a Grid and this happens at the start of the application (this part I think deals with Dispatcher as it is a part of the UI), and then CRUD to a Database.

推荐答案

你不应该使用 Dispatcher.相反,您可以使用 awaitIProgress 将工作委托回 UI 线程.

You should not use Dispatcher. Instead, you can use await or IProgress<T> to delegate work back to the UI thread.

例如:

private async void b1_Click(object sender, RoutedEventArgs e)
{
  // We are starting on the UI thread here.
  txtb1.Text = "";
  var watch = System.Diagnostics.Stopwatch.StartNew();

  await writeintxtbx();

  // After the await completes, we return to the UI thread because await captured the UI context.

  watch.Stop();
  var elapsedtm = watch.ElapsedMilliseconds;

  // Since we're on the UI thread, we can update UI elements.
  txtb1.Text += $"TOTAL TIME {elapsedtm} \n\n\n";
}

如果您需要使用进度更新来更新 UI 元素,请使用 IProgress:

If you need to update UI elements with progress updates, then use IProgress<T>:

private async Task writeintxtbx()
{
  var progress = new Progress<string>(x => txtb1.Text += x);
  await Task.Run(() => Task1(progress));
  await Task.Run(() => Task2(progress));
}

private void Task1(IProgress<string> progress)
{
  progress?.Report($"Task 01 Done \n\n");
}

private void Task2() 
{
  progress?.Report($"Task 2 done \n\n");
}

这篇关于WPF 中的调度程序和异步等待的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆