25

我想编写一个将await变量设置为true的方法。

这是伪代码。

bool IsSomethingLoading = false
SomeData TheData;

public async Task<SomeData> GetTheData()
{
   await IsSomethingLoading == true;
   return TheData;
}

TheData将由 Prism 事件与IsSomethingLoading变量一起设置。

我调用了该GetTheData方法,但我希望它运行异步(现在,如果数据尚未准备好,它只会返回 null。(这会导致其他问题。)

有没有办法做到这一点?

4

4 回答 4

25

在许多这样的情况下,您需要的是一个TaskCompletionSource.

您可能有一种方法能够在某个时间点生成数据,但它不使用任务来完成它。也许有一个方法接受提供结果的回调,或者触发一个事件以指示有结果,或者只是使用 aThreadThreadPool您不倾向于重新考虑使用的代码Task.Run

public Task<SomeData> GetTheData()
{
    TaskCompletionSource<SomeData> tcs = new TaskCompletionSource<SomeData>();
    SomeObject worker = new SomeObject();
    worker.WorkCompleted += result => tcs.SetResult(result);
    worker.DoWork();
    return tcs.Task;
}

虽然您可能需要/想要向TaskCompletionSource工作人员或其他班级提供,或以其他方式将其暴露给更广泛的范围,但我发现通常不需要它,即使它在适当的时候是一个非常强大的选项。

您也可以使用Task.FromAsync基于异步操作创建任务,然后直接返回该任务,或者await在您的代码中返回。

于 2013-02-27T21:47:58.267 回答
16

您可以使用TaskCompletionSource作为信号,并且await

TaskCompletionSource<bool> IsSomethingLoading = new TaskCompletionSource<bool>();
SomeData TheData;

public async Task<SomeData> GetTheData()
{
   await IsSomethingLoading.Task;
   return TheData;
}

在您的 Prism 活动中,请执行以下操作:

IsSomethingLoading.SetResult(true);
于 2013-02-27T21:48:55.310 回答
1

这对我有用:

while (IsLoading) await Task.Delay(100);
于 2021-05-13T18:10:32.523 回答
0

我提出了一个非常简单的解决方案,但不是回答原始问题的最佳解决方案,如果您不关心速度性能:

...
public volatile bool IsSomethingLoading = false;
...
public async Task<SomeData> GetTheData()
{
    // Launch the task asynchronously without waiting the end
    _ = Task.Factory.StartNew(() =>
    {
        // Get the data from elsewhere ...
    });

    // Wait the flag    
    await Task.Factory.StartNew(() =>
    {
        while (IsSomethingLoading)
        {
            Thread.Sleep(100);
        }
    });

   return TheData;
}

重要提示:@Theodor Zoulias 建议:IsSomethingLoading应使用volatile关键字声明,以避免编译器优化和从其他线程访问时潜在的多线程问题。有关编译器优化的更多信息,请参阅本文: 理论与实践中的 C# 内存模型

我在下面添加了一个完整的测试代码:

XAML:

<Label x:Name="label1" Content="Label" HorizontalAlignment="Left" Margin="111,93,0,0" VerticalAlignment="Top" Grid.ColumnSpan="2" Height="48" Width="312"/>

测试代码:

public partial class MainWindow : Window
{
    // volatile keyword shall be used to avoid compiler optimizations
    // and potential multithread issues when accessing IsSomethingLoading
    // from other threads.
    private volatile bool IsSomethingLoading = false;

    public MainWindow()
    {
        InitializeComponent();

        _ = TestASyncTask();
    }

    private async Task<bool> TestASyncTask()
    {
        IsSomethingLoading = true;

        label1.Content = "Doing background task";

        // Launch the task asynchronously without waiting the end
        _ = Task.Factory.StartNew(() =>
        {
            Thread.Sleep(2000);
            IsSomethingLoading = false;
            Thread.Sleep(5000);
            HostController.Host.Invoke(new Action(() => label1.Content = "Background task terminated"));
        });
        label1.Content = "Waiting IsSomethingLoading ...";

        // Wait the flag    
        await Task.Run(async () => { while (IsSomethingLoading) { await Task.Delay(100); }});
        label1.Content = "Wait Finished";

        return true;
    }

}

/// <summary>
/// Main UI thread host controller dispatcher
/// </summary>
public static class HostController
{
    /// <summary>
    /// Main Host
    /// </summary>
    private static Dispatcher _host;
    public static Dispatcher Host
    {
        get
        {
            if (_host == null)
            {
                if (Application.Current != null)
                    _host = Application.Current.Dispatcher;
                else
                    _host = Dispatcher.CurrentDispatcher;
            }

            return _host;
        }
    }
}
于 2020-04-29T21:31:43.253 回答