Tasks和Threads我真的不是很懂。
我在三层嵌套的 for
中有一个方法,我想在不同的线程/任务中多次运行,但是我传递给该方法的变量变得疯狂,让我用一些代码来解释:
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
确实做了很多事情,比如计算一些数字的阶乘,写入不同的文档并用组合列表匹配响应以及调用其他小方法,它也有一些返回值( bool 值),但我现在不关心它们。
问题是没有任务结束,就像每次嵌套调用它刷新自身的方法一样,删除以前的实例。
它还给出一个错误,“尝试除以 0”,值超过由 FOR 分隔的值,例如 a=71, b=7, c=11
和所有变量为空(这就是为什么除以零)。我真的不知道怎么解决。
最佳答案
问题是,您正在使用一个已经或将要在您的 closure 之外修改的变量/ lambda 。你应该得到一个警告,说“访问修改后的闭包”。
您可以通过先将循环变量放入局部变量并使用它们来修复它:
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# - 在 C# 中同时运行同一方法的多个实例而不会丢失数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15204198/