I need to handle concurrent requests by waiting for the result of an already running operation. Is this code safe or does it contain bugs?
private readonly object _gettingDataTaskLock = new object();
private Task<Data> _gettingDataTask;
public virtual Data GetData()
{
Task<Data> inProgressDataTask = null;
lock (_gettingDataTaskLock)
{
if (_gettingDataTask == null)
{
_gettingDataTask = Task.Factory.StartNew(() => GetDataInternal());
_gettingDataTask.ContinueWith((task) =>
{
lock (_gettingDataTaskLock)
{
_gettingDataTask = null;
}
},
TaskContinuationOptions.ExecuteSynchronously);
}
inProgressDataTask = _gettingDataTask;
}
try
{
return inProgressDataTask.Result;
}
catch (AggregateException ex)
{
_logger.ErrorException(ex, "An error occurs during getting full data");
throw ex.InnerException;
}
}