.net - 当两个任务中的任何一个完成时,需要在我的 Form 类中调用一个方法
问题描述
在表单中,在 Load 事件中,我需要启动两个任务(如下所示)。然后让它在任一完成时调用我的表单对象。我怎样才能做到这一点?
或者,我不明白这一点吗?我确实将我的加载方法设置为异步。那么这是否意味着它立即从对 Load 的调用中返回,但没有完成,因为我用 await 调用了 LoadMetadata?因此 Form 处理得很好,但 Load 在其中一项任务完成之前不会执行所有代码。
是这样吗?所以我没事。(我可能已经习惯了我必须围绕线程做的所有家务,我让这变得比现在更复杂。)
private async void LoadingMetadata_Load(object sender, EventArgs e)
{
// load the metadata - this creates a task and returns.
var result = await LoadMetadata(this, profile, source.Token);
}
private static async Task<bool> LoadMetadata(LoadingMetadata dlg, DataSourceProfile profile, CancellationToken cancellationToken)
{
// We create a TaskCompletionSource of decimal
var taskCompletionSource = new TaskCompletionSource<bool>();
// Registering a lambda into the cancellationToken
cancellationToken.Register(() =>
{
// We received a cancellation message, cancel the TaskCompletionSource.Task
taskCompletionSource.TrySetCanceled();
});
// load the metadata
Task<bool> task = Task.Run(() => { profile.ReloadMetadata(); return true; } );
// Wait for the first task to finish among the two
var completedTask = await Task.WhenAny(task, taskCompletionSource.Task);
// If the completed task is our long running operation we set its result.
if (completedTask == task)
{
// Extract the result, the task is finished and the await will return immediately
var result = await task;
// Set the taskCompletionSource result
taskCompletionSource.TrySetResult(result);
}
// close the dialog
bool success = await taskCompletionSource.Task;
dlg.DialogResult = success ? DialogResult.OK : DialogResult.Cancel;
dlg.Close();
// Return the result of the TaskCompletionSource.Task
return success;
}
解决方案
推荐阅读
- java - Files.walk - 过滤仅存在于给定列表中的文件
- php - 在Linux中安装Lua并实现PHP Lua Extension
- rust - Rust 是否可以在过程宏代码中调用宏?
- android - 在 null 上调用了方法“_debugTypesAreRight”
- json - 如何在结构中检索单个变量值
- javascript - 创建简单的数据库/方式来存储用户帐户信息的 html 信息并生成用户个人资料页面
- flutter - 钻石风格的 Flutter Avatar
- python - 为什么我的代码在打开时一直退出?*在游戏中*
- javascript - three.js - 为什么光线投射器无法识别加载的对象?
- react-native - 调整反应本机论文BottomNavigation中的图标大小