开发者

Only last task runs!

I am in desperate to find a solution to my problem.

Following is the code which generates different task for each item in List<AccountContactView>.

List<AccountContactViewModel> selectedDataList
    = DataList.Where(
        dataList => (bool) dataList.GetType()
         开发者_JAVA技巧                          .GetProperty("IsChecked")
                                   .GetValue(dataList, new object[0]) == true
      ).ToList();

this.IsEnabled = false;

Task validateMarked = Task.Factory.StartNew(() =>
{
    foreach (AccountContactViewModel viewModel in selectedDataList)
    {
        if (viewModel != null)
        {
            Task validate = Task.Factory.StartNew(
                () => ValidateAccount(viewModel),
                (TaskCreationOptions)TaskContinuationOptions.AttachedToParent);
        }
    }
});

validateMarked.ContinueWith(x => this.IsEnabled = true);

Now my problem is when it runs, it only runs for the last item in the array. Any idea about what I am doing wrong?

I don't want to use Parallel.ForEach becuase it doesn't provide the necessary effect of parallelism to increase the progress bar based on completion of each task.


This might be a lambda scope problem.

Have you tried to assign the viewModel to a local variable before passing it to the StartNew method

...
Task validateMarked = Task.Factory.StartNew(() =>
{
    foreach (AccountContactViewModel viewModel in selectedDataList)
    {
        var localViewModel = viewModel;
        if (localViewModel != null)
        {
            Task validate = Task.Factory.StartNew(
                () => ValidateAccount(localViewModel),
                (TaskCreationOptions)TaskContinuationOptions.AttachedToParent);
        }
    }
});
...
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜