我怎样才能等待直到我收到 callback/notification 而不忙等待?

How can I await until I receive a callback/notification without busy-waiting?

我明白我如何 await 在库代码上等待网络请求或其他长时间的 运行 操作完成,但我如何 await 自己长时间-运行 操作无需忙等待?


这是忙等待解决方案。我怎样才能让它成为事件驱动的?

public async Task<DataBlock> ClickSend() {
    // await until someone calls DataReceived()
    while (_Block == null) {
        await Task.Yield();
    }
    return _Block;
}

// Something external calls this function.
// Once called, ClickSend should complete with this data.
public void DataReceived(DataBlock data_block) {
    _Block = data_block;
}
DataBlock _Block = null;

(这道题和 which is asking how to await on event handlers, but very similar to 完全不同。)

Generally in concurrency “未来”是 return 值的占位符,它有一个关联的“承诺”,该承诺将实现以传递最终的 return 值。

在 C# 中,它们有不同的名称:future 是一个 Task 和

您可以创建一个承诺,等待它,然后在收到回调时实现它:

TaskCompletionSource<DataBlock> _Promise = new TaskCompletionSource<DataBlock>();

public async Task<DataBlock> ClickSend() {
    DataBlock block = await _Promise.Task;
    return block;
}

public void DataReceived(DataBlock data_block) {
    _Promise.TrySetResult(data_block);
}

Here's an executable example.