首页 > 解决方案 > 当两个任务中的任何一个完成时,需要在我的 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;
    }

标签: .netasync-awaittask

解决方案


推荐阅读