等待和异步阻止UI

等待和异步阻止UI

本文介绍了等待和异步阻止UI的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编写了一个winforms小程序,用于搜索磁盘上的文件(出于问题的考虑,哪个文件并不那么重要).问题是它甚至可以是100,000个文件左右.因此此操作需要时间.

I wrote a little winforms application that search for files on the disk (what file is not that important for the sake of the question). the problem is the that it can be even 100,000 files or so. so this operation takes time.

我想要实现的是将搜索操作作为异步操作执行,而不是阻塞UI线程,以免表单卡住.

What I want to achieve is to do the search operation as an async operation and not to block the UI thread so the form won't get stuck.

我可以使用backgroundWorker来做到这一点,但是由于某种原因,不能使用async \ await机制来实现.

I can do this with the backgroundWorker but for some reason not with the async\await mechanism.

这是我的代码:

private async void button_FindFiles_Click(object sender, EventArgs e)
{
    await SearchFilesUtil.SearchPnrFilesAsync(this.textBox_mainDirectory.Text);
    MessageBox.Show("After SearchPnrFilesAsync");
}

public async static Task SearchPnrFilesAsync(string mainDir)
{
    foreach (string file in Directory.EnumerateFiles(mainDir, ".xml", SearchOption.AllDirectories))
    {
        var fileContenet = File.ReadAllText(file);
        var path = Path.Combine(@"C:\CopyFileHere", Path.GetFileName(file));
        using (StreamWriter sw = new StreamWriter(path))
        {
            await sw.WriteAsync(fileContenet);
        }
    }
}

为什么UI线程卡住并且不立即显示MessageBox?我想念什么?

Why is the UI thread get stuck and not displaying the MessageBox immediately?what am I missing ?

推荐答案

使用async关键字本身标记SearchPnrFilesAsync的事实并不能神奇地开始在单独的任务中异步执行该方法.

The fact of marking SearchPnrFilesAsync with async keyword itself doesn't magically starts execution ot this method asynchronously in separate task.

实际上,除了sw.WriteAsync之外,SearchPnrFilesAsync中的所有代码都在UI线程中执行,因此将其阻止.

In fact, all of the code in SearchPnrFilesAsync except sw.WriteAsync executes in UI thread thus blocking it.

如果您需要在单独的任务中执行整个方法,则可以通过如下包装来实现:

If you need to execute your whole method in separate task, you can do it by wrapping like:

public async static Task SearchPnrFilesAsync(string mainDir)
{
   await Task.Run(() => your_code_here);
}

这篇关于等待和异步阻止UI的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-16 07:12