【发布时间】:2021-05-27 08:30:38
【问题描述】:
我有一个 wpf 应用程序,其中一个功能是复制文件。它可以正常运行,但有时会冻结 UI,因此我正在尝试向其添加 async/await 功能。
这是代码:
if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
string[] files = filePickedTextBox.Text.Split('\n');
await Task.Run(() =>
{
foreach (var file in files)
{
try
{
AddValueLoadingBar(20, true);
File.Copy(file, Path.Combine(dialog.SelectedPath, Path.GetFileName(file)));
newDirTextBox.Text = Path.Combine(dialog.SelectedPath, Path.GetFileName(file));
}
catch(Exception ex)
{
newDirTextBox.Text = ex.ToString();
}
finally
{
AddValueLoadingBar(100, true);
}
}
});
我尝试在多个位置添加 dispatcher.invoke,但在需要与文本框对话时,总是收到一个错误,提示它正在请求来自不同线程的请求。
我已经在这工作了几个小时,并且在网上搜索了许多 stackoverflow 线程和其他文档,但我不知道如何实现它。
我也知道我的进度条实现很糟糕......但我现在并不担心,因为我一开始就无法让它运行而不冻结。
任何帮助都会很棒。
谢谢
【问题讨论】:
-
这不是一个winform,所以它不使用backgroundworker。编辑主要帖子以说明其 wpf
-
这能回答你的问题吗? Cross-thread operation not valid: Control accessed from a thread other than the thread it was created on。您应该使用
BeginInvoke而不是Invoke,因为后者会导致线程死锁 -
@MattU -
BackgroundWorker不再是做这种事情的方法。现在有很多更好的选择。 -
@user15919119 - 为什么要在 WPF 中使用
System.Windows.Forms对话框? -
我会改变的。谢谢!
标签: c# wpf async-await invoke