简体   繁体   English

多个任务的C#异步问题

[英]c# async issue with multiple tasks

I am trying to iterate over a list and trying to get data from async method. 我正在尝试遍历列表,并尝试从异步方法获取数据。 Following is the code : 以下是代码:

var tasks = listOfStrings.Select(async currentString => {

       //creating an object RequestDataObj
        RequestDataObj request = new RequestDataObj();

       //filling RequestDataObj with some request data based on currentString

       //making async call and getting data in resultDataObj 
       var resultDataObj = await ApiCall.GetDataAsync(request, currentString);

       //saving resultDataObj + currentString to database synchronously
  });

await Task.WhenAll(tasks);
//doing some other operations here

Problem is that in database the value of currentString is always the last item of listOfStrings. 问题在于,在数据库中,currentString的值始终是listOfStrings的最后一项。 Am I doing anything wrong? 我做错什么了吗? Please help. 请帮忙。

Thanks 谢谢

I believe you have a closure issue here. 我相信您在这里遇到关闭问题。 Try this instead: 尝试以下方法:

var taskList = new List<Task>();
foreach (var myString in listOfStrings)
{
    // Avoid closure issue
    var temp = myString;
    taskList.Add(Task.Factory.StartNew(async object stringObject => {
        var currentString = stringObject as string;
        //creating an object RequestDataObj
        RequestDataObj request = new RequestDataObj();

        //filling RequestDataObj with some request data based on currentString

        //making async call and getting data in resultDataObj 
        var resultDataObj = await ApiCall.GetDataAsync(request, currentString);

        //saving resultDataObj + currentString to database synchronously
    }, temp));
}

await Task.WhenAll(taskList);
//doing some other operations here

There may be typos in the above; 上面可能有错别字; haven't tested it. 还没有测试

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM