c#在for循环中等待

BeL*_*ver 1 c# async-await

如果缺少信息,我有一个需要更新的项目列表。但是,我正在调用 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;
}
Run Code Online (Sandbox Code Playgroud)

Gui*_*rez 5

您可以通过多个任务异步获取多个地图点(注意它需要转换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));
}
Run Code Online (Sandbox Code Playgroud)

如果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));
}
Run Code Online (Sandbox Code Playgroud)

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