gpt4 book ai didi

c# - 无法从 'System.Threading.Tasks.Task' 转换为 'System.Collections.Generic.Dictionary'

转载 作者:太空宇宙 更新时间:2023-11-03 18:28:44 25 4
gpt4 key购买 nike

我相信我可能只是语法错误,但我想做的是创建一个在另一个任务完成后运行的任务。

对于列表中的每个 100 数组,我都有一个任务。它启动一个新线程,将该数组传递给一个方法。该方法在完成时返回一个字典。我正在尝试创建一个任务以在该方法完成后运行,它将返回的字典传递给一个单独的方法来完成更多工作。

static void Main(string[] args)
{
try
{
stopwatch = new Stopwatch();
stopwatch.Start();
while (true)
{
startDownload();
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}

public static async void startDownload()
{
try
{

DateTime currentDay = DateTime.Now;

if (Helper.holidays.Contains(currentDay) == false)
{
List<string> markets = new List<string>() { "amex", "global", "nasdaq", "nyse" };

Parallel.ForEach(markets, async market =>
{
try
{

IEnumerable<string> symbolList = Helper.getStockSymbols(market);
var historicalGroups = symbolList.Select((x, i) => new { x, i })
.GroupBy(x => x.i / 100)
.Select(g => g.Select(x => x.x).ToArray());

Task<Dictionary<string, string>>[] historicalTasks =
historicalGroups.Select(x => Task.Run(() =>
Downloads.getHistoricalStockData(x, market)))
.ToArray();

Dictionary<string, string>[] historcalStockResults = await
Task.WhenAll(historicalTasks);

foreach (var dictionary in historcalStockResults)
{
Downloads.updateSymbolsInDB(dictionary);
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
});

await Task.Delay(TimeSpan.FromHours(24));
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}

最佳答案

如果您已经在使用 await,我建议您根本不要使用 ContinueWith。原因是您的代码最终变得冗长。

相反,尽可能使用await。代码最终是这样的:

var historicalGroups = symbolList
.Select((x, i) => new { x, i })
.GroupBy(x => x.i / 100)
.Select(g => g.Select(x => x.x).ToArray());

var historicalTasks = historicalGroups.Select(x => Task.Run(() =>
Downloads.getHistoricalStockData(x, market)))
.ToArray();

var historcalStockResults = await Task.WhenAll(historicalTasks);

foreach (var dictionary in historcalStockResults)
{
Downloads.updateSymbolsInDB(dictionary);
}

请注意使用 Task.Run 而不是 Task.Factory.StartNew。您应该改用它。更多关于 here

编辑:

如果你需要每 24 小时执行一次这段代码,在上面添加一个 Task.Delayawait :

await Task.Delay(TimeSpan.FromHours(24));

编辑 2:

您的代码不工作的原因是因为 startDownloadasync void,而您没有等待它。因此,无论您的 Task.Delay 是什么,您的 while 循环都会不断迭代。

因为您在控制台应用程序中,所以您不能 await 因为 Main 方法不能是异步的。因此,要解决此问题,请将 startDownload 更改为 async Task 而不是 async void,然后 Wait 返回任务。请注意,使用 Wait 应该几乎永远不会使用,除了特殊情况(例如在控制台应用程序中运行时):

public async Task StartDownload()

然后

while (true)
{
StartDownload().Wait();
}

另请注意,混合使用 Parallel.Foreachasync-await 并不总是最好的主意。您可以在 Nesting await in Parallel.ForEach 中阅读更多相关信息

关于c# - 无法从 'System.Threading.Tasks.Task' 转换为 'System.Collections.Generic.Dictionary<string,string>',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27644561/

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