Thread locking in C sharp

L

linuxfedora

When i try to do something like that:

Button On Click->Call ShowInfo();

class testing
{
private Object locker= new Object();

public void ShowInfo()
{
Console.WriteLine("Begin");

using(locker)
{
for (int j = 0; j < 10; j++)
{
Console.WriteLine("j=" + j);
}
}

Console.WriteLine("End");
}
}

then when i click the button very quick, the result will be like that:

Begin
j=0;
j=1;
Begin
j=0;
Begin

but the what the result i wanted is
Begin
j=0;
j=1;
j=2;
j=3;
j=4;
j=5;
j=6;
j=7;
j=8;
j=9;
End
Begin
j=0
..
..

What is wrong with my code? and how to do the same thing?
How to ensure some codes are completed before another thread is trying
to enter the code?Thanks
 
P

Patrice

If "using" is not a typo try "lock" instead ;-)

If this is a typo, make sure you don't create a new testing class instance
in which case you would lock another object...
 
P

Peter Duniho

[...]
What is wrong with my code? and how to do the same thing?
How to ensure some codes are completed before another thread is trying
to enter the code?Thanks

As Patrice says, you need to use the "lock()" statement to protect a
block of code, not "using()".

Beyond that, you haven't explained your situation very well. Does the
Button.Click event handler simply call ShowInfo() directly? Or does it
create a new thread for each click?

I'm assuming the latter, based on the output you described, but you
don't actually explain that anywhere in your post. If you want better
answers you need to be more specific in your questions.

Pete
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top