使用多线程调用方法时的Datamismatch [英] Datamismatch when called method using multithreading
问题描述
请在下面找到以下代码段并帮助解决它。
Program.cs:
< pre lang =c#> class 计划
{
静态 void Main( string [] args)
{
for ( int i = 0 ; i < 5 ; i ++)
{
Class1 obj = new Class1();
new 线程(()= > obj.Show(i))。开始( );
}
Console.ReadLine();
}
}
Class1:
class Class1
{
public void 显示( int i)
{
Console.WriteLine(< span class =code-string> 显示: + i);
Thread.Sleep(i * 100 );
}
}
例外输出:
显示:0
显示:1
显示:2
显示:3
显示:4
但是由于线程我没有得到上面的结果
结果是不可预测的像
显示:3
显示:3
显示:3
显示:5
显示:4
任何人都可以告诉我,如何解决这类问题?
你已经捕获了循环变量关闭。这不会像你期望的那样工作:
关闭被认为有害的循环变量:Eric Lippert的博客 [ ^ ]
在.NET 4.5中,这是针对foreach
循环修复的;但是,for
循环保留旧的行为。
要修复它,你需要创建一个循环变量,并在闭包中使用该副本:
for ( int i = 0 ; i < 5 ; i ++)
{
int iCopy = i;
Class1 obj = new Class1();
new 线程(()= > obj.Show(iCopy))。开始( );
}
尝试更改方法Show to this。
public void 显示( int i)
{
Console.WriteLine( 显示: + i);
Thread.Sleep(i * 100 );
Console.WriteLine( 显示: + i);
}
在打印之前放入睡眠更有意义。
我试过这个并且正在工作根据你的预期。
for(int i = 1; i< = 10; i ++)
{
Class1 obj = new Class1() ;
obj.Show(i);
//新主题(()=> obj.Show(i))。Start();
}
Console.ReadLine();
Please find below code snippet and help to resolve it.
Program.cs:
class Program
{
static void Main(string[] args)
{
for (int i = 0; i < 5; i++)
{
Class1 obj = new Class1();
new Thread(() => obj.Show(i)).Start();
}
Console.ReadLine();
}
}
Class1:
class Class1
{
public void Show(int i)
{
Console.WriteLine("Show: " + i);
Thread.Sleep(i * 100);
}
}
Excepted Output:
Show: 0
Show: 1
Show: 2
Show: 3
Show: 4
But due to threading i am not getting result in above way
the result is unpredictable like
Show: 3
Show: 3
Show: 3
Show: 5
Show: 4
Can any one let me know, how to resolve this kind of issue?
You have captured the loop variable in a closure. That doesn't work as you'd expect:
Closing over the loop variable considered harmful : Eric Lippert’s Blog[^]
In .NET 4.5, this was fixed forforeach
loops; however,for
loops retain the old behaviour.
To fix it, you need to create a copy of the loop variable, and use that copy in your closure:
for (int i = 0; i < 5; i++) { int iCopy = i; Class1 obj = new Class1(); new Thread(() => obj.Show(iCopy)).Start(); }
Try to change the method Show to this.
public void Show(int i) {Console.WriteLine("Show: " + i);Thread.Sleep(i * 100); Console.WriteLine("Show: " + i); }
It makes more sense to put the sleep before the print out.
I have tried this and working as per your expecteation.
for (int i = 1; i <= 10; i++) { Class1 obj = new Class1(); obj.Show(i); //new Thread(() => obj.Show(i)).Start(); } Console.ReadLine();
这篇关于使用多线程调用方法时的Datamismatch的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!