c#具有多个任务的异步问题

时间:2014-01-22 18:57:20

标签: c# asp.net-mvc asynchronous

我正在尝试迭代列表并尝试从异步方法获取数据。以下是代码:

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

问题是在数据库中,currentString的值始终是listOfStrings的最后一项。我做错了吗?请帮忙。

由于

1 个答案:

答案 0 :(得分:1)

我相信你有一个关闭问题。试试这个:

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

上面可能有拼写错误;尚未测试过。