如何使用Task而不是Lazy?

时间:2015-12-21 12:00:54

标签: c# task lazy-evaluation

对于每个唯一的凭证集合,最多可以有一个正在进行的GetData调用,其中一个调用的结果在准备就绪时返回给所有排队的服务员。

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);
        }
    }
}

当我使用Lazy时,我的所有单元测试都能正常工作。但是我想使用Task,所以我改变了以下几行:

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

它不起作用。如何将我的代码更改为等效但使用Task,而不是async/await

0 个答案:

没有答案