1

For each unique set of credentials there can be at most one GetData call in progress, with the result from that one call returned to all queued waiters when it is ready.

private readonly ConcurrentDictionary<MetadataCredentials, Lazy<AgentMetadata>> _credentialToMetadataMap =
        new ConcurrentDictionary<MetadataCredentials, Lazy<AgentMetadata>>();

public virtual AgentMetadata GetCurrent(MetadataCredentials metadataCredentials)
{
    var agentMetadata = new Lazy<AgentMetadata>(() => GetData(metadataCredentials));
    var lazyMetadata = _credentialToMetadataMap.GetOrAdd(metadataCredentials, agentMetadata);

    bool isAdded = ReferenceEquals(agentMetadata, lazyMetadata);

    try
    {
        return lazyMetadata.Value;
    }
    catch (AggregateException ex)
    {
       throw ex.InnerException;
    }
    finally
    {
            // Only the thread which created the cache value is allowed to remove it, to prevent races.
        if (isAdded)
        {
            _credentialToMetadataMap.TryRemove(metadataCredentials, out lazyMetadata);
        }
    }
}

All of my unit tests works fine when I use Lazy. But I want to use Task, so I change the following lines:

ConcurrentDictionary<MetadataCredentials, Task<AgentMetadata>> _credentialToMetadataMap;
var agentMetadata = new Task<AgentMetadata>(() => GetData(metadataCredentials));
try
{
     lazyMetadata.Wait();
     return lazyMetadata.Result;
}

It doesn't work. How to change my code to equivalent but with Task, without async/await?

Anatoly
  • 1,908
  • 4
  • 25
  • 47
  • 5
    Starting tasks via the `Task` constructor is generally a bad idea (`Task.Run`) is preferred. Plus calling `Wait` is also a very bad idea so it seems your best starting point is to read up on `Task`s. Also, "it doesn't work" is a terrible description for any problem. Be specific - you are asking people for help. Make it easier for them to help you by including the actual details. – Daniel Kelley Dec 21 '15 at 12:03
  • Why do you want to use `Task` instead of `Lazy`? The two are not interchangeable. – Yuval Itzchakov Dec 21 '15 at 12:07
  • It looks like déjà vu. – Dennis Dec 21 '15 at 12:08
  • @DanielKelley I would like to understand if my final result will be the same – Anatoly Dec 21 '15 at 15:00
  • @YuvalItzchakov I know that they are not interchangeable. But I would like to compare final result. – Anatoly Dec 21 '15 at 15:01

0 Answers0