c# - 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);});
解决方案
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();
}
}
推荐阅读
- reactjs - 如何设计 redux-saga 和 socket-io 动作?
- android - Meteor run android-device:请求的资源上不存在“Access-Control-Allow-Origin”标头
- jquery - jQuery mapael 动态绘图
- mysql - 光标在过程中被中断 - MySQL
- node.js - Elastic Beanstalk - 访问 web 应用程序时出现 502 错误,找不到 package.json
- iis - 如何拒绝在 Windows 2012 R2 上运行的 IIS 中的 http get 请求?
- python - Python:创建邮件 - 显示邮件但不发送 - smtplib + MIMEmultipart + Outlook
- ruby-on-rails - 使用多步远程链接时处理后退按钮
- mariadb - 具有多集群设置的 MaxScale
- c# - 在 C# 中将字节数组转换为字符串,反之亦然