简体   繁体   English

Task.Run 仍然冻结 UI

[英]Task.Run still freezing UI

So, i'm trying to convert a large byte array into it's base64 encoded variant.所以,我正在尝试将一个大字节数组转换为它的 base64 编码变体。 But no matter what i try, it seems to freeze up my UI every time it runs.但无论我尝试什么,它似乎每次运行时都会冻结我的 UI。

This is what i've got currently:这就是我目前所拥有的:

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;

        }
    }

So, the line that freezes everything up is:因此,冻结所有内容的行是:

txtOutput.Text = await Task.Run(() => {return Convert.ToBase64String(fileBytes);});
 File.ReadAllBytes(path[0])

Could be a bottle neck you can use async operation for read files Here is an example how to read file async可能是一个瓶颈,您可以使用异步操作来读取文件这是一个如何读取文件异步的示例

        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();  
        }  
    }

Right, so it turns out that my problem was using a textbox for writing the string to instead of a richtextbox.对,所以事实证明我的问题是使用文本框将字符串写入而不是富文本框。 This fixed my problem.这解决了我的问题。 Thanks for your answers.感谢您的回答。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM