0

I have a method which I only want a thread to run one at a time.

The problem is, the execution of this method is coupled with a Command, so when a user presses a button a few times in a row really fast, my method gets called a few times in a row by the same thread. Locking doesn't work in this case since the same thread just gets the lock time and time again. I find it odd that the same method is called a few times in a row by the same thread while earlier calls of the method haven't finished yet.

Is there any way to force a method to run only one at a time from a single thread?

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
Davio
  • 4,609
  • 2
  • 31
  • 58
  • are you sure you remain on your UI thread when clicking this button? – JMan Feb 12 '13 at 10:37
  • 3
    Your question is pretty unclear - if it's within the same thread, you've either got odd re-entrancy, or you're diagnosing this incorrectly... – Jon Skeet Feb 12 '13 at 10:37
  • Are you using WinForms? – Carsten Feb 12 '13 at 10:38
  • Are you sure that its the same thread accessing the method concurrently, I didn't think that was possible. What implementation of locking have you tried? – RobJohnson Feb 12 '13 at 10:39
  • Do you have some code to show us? It might help us understand. – mortb Feb 12 '13 at 10:39
  • John is right. Here, it is likely that you mean that when you press the button several times multiple [but different] threads are being spun off. I think you can provent this wil a global boolean in your relevent class. If the boolean `IsRunning` is true, return to caller... – MoonKnight Feb 12 '13 at 10:53
  • Smells badly of 'DoEvents' to me :(( – Martin James Feb 12 '13 at 11:29
  • 1
    Based on your question, I am presuming it is WPF. Your issue is more of a UI design issue. If you want pressing a button to only trigger an event once, you disable it after the first press, until the method complete. – TYY Feb 12 '13 at 11:48
  • @JonSkeet - I got inspired by your answer on re-entrancy earlier.. so I asked question - whether a thread can be hijacked and got it closed. I am sure only GC and the TPL scheduler (in the case you described) can do it.. but couldn't make it through :)) users with large scores aren't always those with brains (see this question as an example) – Boppity Bop Feb 14 '13 at 03:33
  • @BoppityBop: I'm not at all sure what you mean. Are you suggesting that what I said is incorrect? Which bit, precisely? – Jon Skeet Feb 14 '13 at 06:44
  • no I am saying that you were correct but I couldn't ask further whether there are other cases of thread hijacking cos majority simply didn't get it... just ranting. SO is now hugely weird land of little warlords with random quality of brain. – Boppity Bop Feb 14 '13 at 07:02

0 Answers0