await and async blocking the UI

前端 未结 2 1530
北海茫月
北海茫月 2021-01-13 02:26

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 eve

相关标签:
2条回答
  • 2021-01-13 02:48

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

    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);
    }
    
    0 讨论(0)
  • 2021-01-13 02:53

    Why does the UI thread get stuck?

    Probably because you have some blocking work done on the UI thread, such as reading a file.

    Why is my MessageBox not displayed immediately?

    Because that is not how async works. When you await a method, it asynchronously yields control to the caller until the operation is done. When the first await is hit, you start reading files from disk and copying them. await does not mean "execute this on a different thread and continue".

    What you probably want to do is use an asynchronous reading mechanism instead of the blocking File.ReadAllText. You can do this using StreamReader:

    public static async Task SearchPnrFilesAsync(string mainDir)
    {
        foreach (string file in Directory.EnumerateFiles(mainDir, ".xml",
                                                            SearchOption.AllDirectories))
        {
            var path = Path.Combine(@"C:\CopyFileHere", Path.GetFileName(file));
            using (var reader = File.OpenRead(file))
            using (var writer = File.OpenWrite(path))
            {
                await reader.CopyToAsync(writer);
            }   
        }   
    }
    
    0 讨论(0)
提交回复
热议问题