J
Jinlin
I found a interesting problem in C# and couldn't explain it.
The code to reproduce it is very simple:
1. Create a windows application in C#.
2. Listen to the activated event on the default form --- Form1.cs
3. Create a method DoUpdate() which will popup two dialog boxes "Dialog box
one" and "Dialog box two".
4. Call DoUpdate() in the activated event handling.
It will look like the following:
private void Form1_Activated(object sender, System.EventArgs e)
{
this.DoUpdate();
}
private void DoUpdate()
{
lock(this)
{
MessageBox.Show("Dialog box one");
MessageBox.Show("Dialog box two");
}
}
Then, take a guess what will happen after you run the application when you
switch between windows on your machine. The result is pretty supprising for
me. Instead of showing "Dialog box one" and "Dialog box two" in turn as I
expected for a multi-thread situation, it keeps looping "Dialog box one". I
replaced this by another self defined object which doesn't solve the
problem.
If this is a single thread case(get rid of the lock in DoUpdate), the result
is the same. How can it jump from "Dialog box one" to Activated event
without finishing DoUpdate.
Our guess is C# keeping the excuting methods in a stack and somehow gives
the event handling a higher priority.
Could anyone explain this?
-Jinlin
The code to reproduce it is very simple:
1. Create a windows application in C#.
2. Listen to the activated event on the default form --- Form1.cs
3. Create a method DoUpdate() which will popup two dialog boxes "Dialog box
one" and "Dialog box two".
4. Call DoUpdate() in the activated event handling.
It will look like the following:
private void Form1_Activated(object sender, System.EventArgs e)
{
this.DoUpdate();
}
private void DoUpdate()
{
lock(this)
{
MessageBox.Show("Dialog box one");
MessageBox.Show("Dialog box two");
}
}
Then, take a guess what will happen after you run the application when you
switch between windows on your machine. The result is pretty supprising for
me. Instead of showing "Dialog box one" and "Dialog box two" in turn as I
expected for a multi-thread situation, it keeps looping "Dialog box one". I
replaced this by another self defined object which doesn't solve the
problem.
If this is a single thread case(get rid of the lock in DoUpdate), the result
is the same. How can it jump from "Dialog box one" to Activated event
without finishing DoUpdate.
Our guess is C# keeping the excuting methods in a stack and somehow gives
the event handling a higher priority.
Could anyone explain this?
-Jinlin