gpt4 book ai didi

c# - 何时创建新任务

转载 作者:太空狗 更新时间:2023-10-29 20:24:19 25 4
gpt4 key购买 nike

我正在学习 C#.NET 4.5 中的任务并行性,我对 example 有点困惑.这是我不明白的代码:

public static Task<string> DownloadStringAsync(string address)
{
// First try to retrieve the content from cache.
string content;
if (cachedDownloads.TryGetValue(address, out content))
{
return Task.FromResult<string>(content);
}

// If the result was not in the cache, download the
// string and add it to the cache.
return Task.Run(async () => // why create a new task here?
{
content = await new WebClient().DownloadStringTaskAsync(address);
cachedDownloads.TryAdd(address, content);
return content;
});
}

具体来说,我不明白为什么他们将 DownloadStringTaskAsync() 包装在另一个任务中。 DownloadStringTaskAsync() 不是已经在自己的线程上运行了吗?

这是我的编码方式:

public static async Task<string> DownloadStringAsync(string address)
{
// First try to retrieve the content from cache.
string content;
if (cachedDownloads.TryGetValue(address, out content))
{
return content;
}

// If the result was not in the cache, download the
// string and add it to the cache.
content = await new WebClient().DownloadStringTaskAsync(address);
cachedDownloads.TryAdd(address, content);
return content;
}

两者有什么区别?哪个更好?

最佳答案

好吧,该示例专门展示了如何使用 Task.FromResult,您的第二个代码没有使用它。也就是说,我不同意示例中 Task.Run 的用法。

我自己会这样写:

public static Task<string> DownloadStringAsync(string address)
{
// First try to retrieve the content from cache.
string content;
if (cachedDownloads.TryGetValue(address, out content))
{
return Task.FromResult(content);
}

// If the result was not in the cache, download the
// string and add it to the cache.
return DownloadAndCacheStringAsync(address);
}

private static async Task<string> DownloadAndCacheStringAsync(string address)
{
var content = await new WebClient().DownloadStringTaskAsync(address);
cachedDownloads.TryAdd(address, content);
return content;
}

另请注意,该示例使用已过时的 WebClient,在新代码中应将其替换为 HttpClient

总的来说,它看起来像是一个糟糕的 IMO 示例。

关于c# - 何时创建新任务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18721403/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com