gpt4 book ai didi

c# 在 for 循环中等待

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

如果信息缺失,我有一个需要更新的项目列表。但是,我正在调用 Google 位置服务来执行此操作。我想知道如何在可能的情况下异步附加必要的纬度和经度信息

我的代码

public static void PullInfo()
{
foreach (var item in SAPItems)
{
if(item.MDM_Latitude == null || item.MDM_Longitude == null)
{
var point = GetMapPoint(item.AddressLine1 + " " + item.FiveDigitZip);
item.MDM_Latitude = point.Result.Latitude.ToString();
item.MDM_Longitude = point.Result.Longitude.ToString();
}
}

foreach(var item in SAPItems)
Console.WriteLine(item.MDM_Latitude + " " + item.MDM_Longitude);
}

private static async Task<MapPoint> GetMapPoint(string add)
{
var task = Task.Run(() => LocationService.GetLatLongFromAddress(add));
return await task;
}

最佳答案

您可以通过多个任务异步获取多个 map 点(注意它需要将 PullInfo() 转换为 async-await):

public static async Task PullInfo()
{
// Create tasks to update items with latitude and longitude
var tasks
= SAPItems.Where(item => item.Latitude == null || item.Longitude == null)
.Select(item =>
GetMapPoint(item.AddressLine1 + " " + item.FiveDigitZip)
.ContinueWith(pointTask => {
item.MDM_Latitude = pointTask.Result.Latitude.ToString();
item.MDM_Longitude = pointTask.Result.Longitude.ToString();
}));

// Non-blocking await for tasks completion
await Task.WhenAll(tasks);

// Iterate to append Lat and Long
foreach(var item in SAPItems)
Console.WriteLine(item.MDM_Latitude + " " + item.MDM_Longitude);
}

private static Task<MapPoint> GetMapPoint(string add)
{
return Task.Run(() => LocationService.GetLatLongFromAddress(add));
}

如果PullInfo()不能转为async-await,可以强制线程等待结果,但是会阻塞当前线程:

public static void PullInfo()
{
// Create tasks to update items with latitude and longitude
var tasks
= SAPItems.Where(item => item.Latitude == null || item.Longitude == null)
.Select(item =>
GetMapPoint(item.AddressLine1 + " " + item.FiveDigitZip)
.ContinueWith(pointTask => {
item.MDM_Latitude = pointTask.Result.Latitude.ToString();
item.MDM_Longitude = pointTask.Result.Longitude.ToString();
}));

// Wait for tasks completion (it will block the current thread)
Task.WaitAll(tasks.ToArray());

// Iterate to append Lat and Long
foreach(var item in SAPItems)
Console.WriteLine(item.MDM_Latitude + " " + item.MDM_Longitude);
}

private static Task<MapPoint> GetMapPoint(string add)
{
return Task.Run(() => LocationService.GetLatLongFromAddress(add));
}

最后一个代码示例的运行示例:https://ideone.com/0uXGlG

关于c# 在 for 循环中等待,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52082617/

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