Only last task runs!

元气小坏坏 提交于 2019-12-30 22:50:12

问题


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()
                                   .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.


回答1:


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);
        }
    }
});
...


来源:https://stackoverflow.com/questions/6653398/only-last-task-runs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!