首页 > 解决方案 > Task.Run 仍然冻结 UI

问题描述

所以,我正在尝试将一个大字节数组转换为它的 base64 编码变体。但无论我尝试什么,它似乎每次运行时都会冻结我的 UI。

这就是我目前所拥有的:

private async void TxtOutput_DragDrop(object sender, DragEventArgs e)
    {
        string outputText = String.Empty;


        if (e.Data.GetDataPresent(DataFormats.FileDrop))
        {

            string[] path = (string[])e.Data.GetData(DataFormats.FileDrop);
            byte[] fileBytes = File.ReadAllBytes(path[0]);
            txtOutput.Text = await Task.Run(() => {return Convert.ToBase64String(fileBytes);});
            _ = fileBytes;
            _ = path;

        }
    }

因此,冻结所有内容的行是:

txtOutput.Text = await Task.Run(() => {return Convert.ToBase64String(fileBytes);});

标签: c#.netasynchronous

解决方案


 File.ReadAllBytes(path[0])

可能是一个瓶颈,您可以使用异步操作来读取文件这是一个如何读取文件异步的示例

        public async Task ProcessReadAsync()  
    {  
        string filePath = @"temp2.txt";  

        if (File.Exists(filePath) == false)  
        {  
            Debug.WriteLine("file not found: " + filePath);  
        }  
        else  
        {  
            try  
            {  
                string text = await ReadTextAsync(filePath);  
                Debug.WriteLine(text);  
            }  
            catch (Exception ex)  
            {  
                Debug.WriteLine(ex.Message);  
            }  
        }  
    }  

    private async Task<string> ReadTextAsync(string filePath)  
    {  
        using (FileStream sourceStream = new FileStream(filePath,  
            FileMode.Open, FileAccess.Read, FileShare.Read,  
            bufferSize: 4096, useAsync: true))  
        {  
            StringBuilder sb = new StringBuilder();  

            byte[] buffer = new byte[0x1000];  
            int numRead;  
            while ((numRead = await sourceStream.ReadAsync(buffer, 0, buffer.Length)) != 0)  
            {  
                string text = Encoding.Unicode.GetString(buffer, 0, numRead);  
                sb.Append(text);  
            }  

            return sb.ToString();  
        }  
    }

推荐阅读