I have ClassA that has a property called GetData that returns a TaskCompletionSource
Task:
private TaskCompletionSource<Data> _taskCompletionSource = new();
public Task<Data> GetData => _taskCompletionSource.Task;
There is also a method called DataRetrieved where I set the result (let’s assume the data retrieval always returns a valid result, no timing out or exceptions):
public void DataRetrieved
{
...
_data = retrievedData;
_taskCompletionSource.SetResult(_data);
...
}
ClassA also has a Reset method. The point of this method is for ClassA to clear its data and retrieve it again from the data source. It is here that I want to “reset” the _taskCompletionSource so that I can be used again.
public void Reset()
{
_data = null;
_taskCompletionSource = new TaskCompletionSource<Data>();
//Make the call to get fresh data which will eventually call DataRetrieved and _taskCompletionSource.SetResult again...
}
Other classes will use ClassA like so:
await _classA.GetData;
I am not sure how to handle the case where Reset is called but some class may already be awaiting GetData. I can check if _taskCompletionSource.Task.IsCompleted, IsFaulted, or IsCanceled and if so I believe I can just recreate _taskCompletionSource. But what should I do if it is in none of those states?
My main goal is to have consumers calling GetData to block until the data is available. So my first thought went to asyc/await.
7