在C#中同时运行同一方法的乘法实例,而不会丢失数据? [英] Run multiply instances of the same method simultaneously in c# without data loss?

查看:130
本文介绍了在C#中同时运行同一方法的乘法实例,而不会丢失数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我真的不太了解Tasks和Threads. 我在三个嵌套的for级别中都有一个方法,我想在不同的线程/任务中多次运行,但是传递给该方法的变量很疯狂,让我用一些代码来解释:

I really don't understand Tasks and Threads well. I have a method inside three levels of nested for that I want to run multiple times in different threads/tasks, but the variables I pass to the method go crazy, let me explain with some code:

List<int> numbers=new List<int>();
for(int a=0;a<=70;a++)
{
  for(int b=0;b<=6;b++)
  {
    for(int c=0;b<=10;c++)
    {
        Task.Factory.StartNew(()=>MyMethod(numbers,a,b,c));
    }
  }
}
private static bool MyMethod(List<int> nums,int a,int b,int c)
{
    //Really a lot of stuff here
}

这是巢,myMethod确实做了很多事情,例如计算一些数字的阶乘,写入不同的文档以及使用组合列表匹配响应并调用其他小方法,它还具有一些返回值(布尔值),但目前我不在乎它们. 问题在于,没有任务可以结束,就像每次嵌套调用其刷新自身的方法一样,它会删除以前的实例. 它还会给出错误尝试除以0",其值超过以FOR分隔的值,例如a=71, b=7, c=11,并且所有变量均为空(这就是为什么要除以零).我真的不知道该怎么解决.

This is the nest, myMethod really does a lot of things, like calculating the factorial of some numbers, writing into different documents and matching responses with a list of combinations and calling other little methods, it has also some return value (booleans), but I don't care about them at the moment. The problem is that no task reach an end, it's like everytime the nest call the method it refreshes itself, removing previous instances. It also give an error, "try to divide for 0", with values OVER the ones delimited by FORs, for example a=71, b=7, c=11 and all variables empty(that's why divided by zero). I really don't know how to solve it.

推荐答案

问题是,您使用的变量已经在

The problem is, that you are using a variable that has been or will be modifed outside your closure/lambda. You should get a warning, saying "Access to modified closure".

您可以通过将循环变量首先放入本地变量并使用这些变量来解决此问题:

You can fix it by putting your loop variables into locals first and use those:

namespace ConsoleApplication9
{
  using System.Collections.Generic;
  using System.Threading.Tasks;

  class Program
  {
    static void Main()
    {
      var numbers = new List<int>();

      for(int a=0;a<=70;a++)
      {
        for(int b=0;b<=6;b++)
        {
          for(int c=0;c<=10;c++)
          {
            var unmodifiedA = a;
            var unmodifiedB = b;
            var unmodifiedC = c;

            Task.Factory.StartNew(() => MyMethod(numbers, unmodifiedA, unmodifiedB, unmodifiedC));
          }
        }
      }
    }

    private static void MyMethod(List<int> nums, int a, int b, int c)
    {
      //Really a lot of stuffs here
    }
  }
}

这篇关于在C#中同时运行同一方法的乘法实例,而不会丢失数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆