有一种从文件加载数据的方法。它通过调用事件来报告其进度OnFileLoad
public Task UploadDataAsync()
{
return Task.Run(() =>
{
...
if (string.IsNullOrEmpty(FilePath))
{
OnFileLoading?.Invoke($"Error while loading: Path is empty");
...
throw new Exception("Path is emprty");
}
if (!File.Exists(FilePath))
{
OnFileLoading?.Invoke($"Error while loading: File not found");
...
throw new Exception("File not found");
}
OnFileLoading?.Invoke($"Start loading from '{FilePath}'");
...
OnFileLoading?.Invoke("Loaded first line");
OnFileLoading?.Invoke("Loaded second line");
...
OnFileLoading?.Invoke("Loaded n line");
...
OnFileLoading?.Invoke("Loading completed");
});
}
主窗口类有一个用于单击“打开”按钮的事件处理程序。它会创建一个新窗口,显示从文件加载数据的进度。
public async void OpenFileClick(object sender, RoutedEventArgs e)
{
try
{
var dataProvider = IocContainer.GetService<IDataProvider>();
LoadingDataStatusWindow loadingDataStatusWindow = new LoadingDataStatusWindow();
dataProvider.OnFileLoad = loadingDataStatusWindow.UpdateLoadingStatus;
loadingDataStatusWindow.Show();
dataProvider.FilePath = AppGlobalSettings.DataFilePath;
await dataProvider.UploadDataAsync();
items = dataProvider.CircuitItems;
CircuitItemDataGrid.ItemsSource = dataProvider.CircuitItems;
}
catch(Exception ex)
{
LogUtility.LogError(ex);
}
}
窗口进度显示方法LoadingDataStatusWindow:
public void UpdateLoadingStatus(string currentRow)
{
StatusTextBox.Text += currentRow + Environment.NewLine;
}
尝试加载数据时,会发生错误,指示线程正在尝试访问另一个线程拥有的对象。StatusTextBox我试图通过向via添加文本来修复它Dispatcher。但这并没有帮助。
在这种情况下,如何通过异步数据加载将进度输出组织到第二个窗口,使其不会挂起 GUI?
正如@aepot 在评论中非常正确地指出的那样,为了报告操作的进度,使用
Progress<T>它就是为此而设计的,它会将自己编组到所需的上下文中。尝试这样的事情:
并相应地