Possible Duplicate:
How to block Winforms UI while background thread is running
i am using a C# WinForm application
I have a Save button on the screen where the data of the screen is saved to database.
what happens, when user clicks to button application goes to database and saves data. it takes some time.
but mean while if user again click on the Save button the Click event get catched and when the first Click return to main code (after saving database) the caught event get fired..
In short the click event get caught and fired when the thread returns from the first event ( I tried the scenario of enable/disable the button).
How can I stop this behavior.
Regards, Akhil
@Jalal: I tried this code with some modification as
private readonly object _userActivityLocker = new object();
private void btnSave_Click(object sender, EventArgs e)
{
if (System.Threading.Monitor.TryEnter(_userActivityLocker))
{
//note that any sub clicks will be ignored while we are here
try
{
DateTime dt = DateTime.Now;
Thread.Sleep(2000);
Debug.Print("FirstClick {0} Second Click {1}",dt.ToLongTimeString(), DateTime.Now.ToLongTimeString());
//here it is safe to call the save and you can disable the btn
Application.DoEvents();
}
finally
{
System.Threading.Monitor.Exit(_userActivityLocker);
//re-enable the btn if you disable it.
}
}
}
but when i rapidly click on button (i checked with 5 times rapid clicks) 5 click events has been fired and console window is showing
FirstClick 1:30:22 PM Second Click 1:30:24 PM FirstClick 1:30:24 PM Second Click 1:30:26 PM FirstClick 1:30:26 PM Second Click 1:30:28 PM FirstClick 1:30:28 PM Second Click 1:30:30 PM FirstClick 1:30:30 PM Second Click 1:30:32 PM