严重质疑c# 多线程能力
c# 多线程能力 严重质疑,我开了两个优先级一样的线,执行的时候,总有一个线程被长期等待对方执行完了才能执行,c#并没有平均分配给它们资源Thread thread1;
Thread thread2;
public delegate void MyInvoke(string i);
private void button1_Click(object sender, EventArgs e)
{
thread1 = new Thread(new ThreadStart(this.pthread1));
thread1.Priority = ThreadPriority.BelowNormal;
thread1.Start();
thread2 = new Thread(new ThreadStart(this.pthread2));
thread2.Priority = ThreadPriority.BelowNormal;
thread2.Start();
//thread2.Start();
//for (int i = 0; i < 5000; i ++ )
//{
// this.label2.Text = i.ToString();
// this.label2.Update();
//}
}
private void UpdateLable(string i)
{
this.label1.Text = i;
this.label1.Update();
}
private void pthread1()
{
for (int i = 0; i < 5000; i++ )
{
MyInvoke myin = new MyInvoke(this.UpdateLable);
lock (this)
{
IAsyncResult ia = this.BeginInvoke(myin, i.ToString());
this.EndInvoke(ia);
}
}
}
private void UpdateLable2(string i)
{
this.label2.Text = i;
this.label2.Update();
}
private void pthread2()
{
for (int i = 0; i < 5000; i++)
{
MyInvoke myin = new MyInvoke(this.UpdateLable2);
lock (this)
{
IAsyncResult ia = this.BeginInvoke(myin, i.ToString());
this.EndInvoke(ia);
}
}
} 你的代码我没有怎么看,这是我在Consol下面写的代码里面的两个线程是基本平均的
当然,你也可以把Sleep去掉,这样执行的会一大段1然后一大段2 然后再一大段1这样,总的来说也是平衡的
class Program
{
static void Main(string[] args)
{
Thread thread1 = new Thread(new ThreadStart(WriteLine));
thread1.Priority = ThreadPriority.BelowNormal;
thread1.Start();
Thread thread2 = new Thread(new ThreadStart(WriteLine2));
thread2.Priority = ThreadPriority.BelowNormal;
thread2.Start();
}
private static void WriteLine()
{
while (true)
{
Console.WriteLine("thread1");
Thread.Sleep(50);
}
}
private static void WriteLine2()
{
while (true)
{
Console.WriteLine("thread2");
Thread.Sleep(50);
}
}
} 关注下 首先,多线程的调度不是C#的支持,而是OS级别的支持,因此指责C#的多线程能力是不应该的。
其次,你的程序可能存在问题,因为对this对象的锁定尽管是在循环中发生的,但是由于执行时间上的微小差异,因此可能出现某一个线程始终会获得锁定而另一个线程很难获得锁定的情况,因此加入Sleep(),让每个线程沉睡一定的时间是非常必要的,这样可以保证另外一个线程有足够的时间获得锁定。
第三,你调用了阻塞线程的EndInvoke方法,使得线程之间的竞争条件更加容易出现。 好好看看这段代码
lock (this)
{
IAsyncResult ia = this.BeginInvoke(myin, i.ToString());
this.EndInvoke(ia);
}
页:
[1]