I am wondering if it would be appropriate to use the TaskCompletionSource
class in the following example:
Original Code / Without TaskCompletionSource
public async Task GetData()
{
if (!IsLoaded)
{
MyList = await Mediator.Send(new GetData());
IsLoaded = true;
}
}
This function is available as part of a singleton scoped service within my .NET Core Web application. It is possible for multiple objects to use the records in MyList
and will await the GetData()
function before using the list.
You can see from the sample function, that it is possible for the method to be called multiple times while the first call is still awaiting the result from the Mediator request. I want a solution to allow multiple objects to await the same Task. So is it appropriate to use a TaskCompletionSource
object for this purpose?
Refactored Using TaskCompletionSource
private TaskCompletionSource getDataTask;
public async Task VerifyDataIsLoaded()
{
if (getDataTask == null)
{
getDataTask = new TaskCompletionSource();
Task.Factory.StartNew(async () =>
{
await GetData();
getDataTask.TrySetResult();
}
}
return getDataTask.Task;
}
private async Task GetData()
{
MyList = await Mediator.Send(new GetData());
}
This should result in the first call to VerifyDataIsLoaded()
instantiating an instance of the TaskCompletionSource getDataTask
object, kicking off the GetData()
function in a new threaded Task, and returning the getDataTask.Task
property.
Now if any other objects call into VerifyDataIsLoaded()
while the GetData()
function is awaiting the return from the Mediator
object, they will all await the same Task, and prevent any redundant calls to GetData
.
Thoughts?? ... bad idea?? better way??