I use the rawinput to get touch events and want to do something only once when touching the screen. This is an example.
private volatile bool running = false;
private object runLock = new object();
private void OnTouchOnHandler(object sender, EventArgs e)
{
lock (runLock)
{
if (!running)
{
MessageBox.Show("1");
running = true;
}
}
}
I will get several MessageBoxes when I touch the screen at first three or four times. That’s really strange. Why lock and volatile variables dont work at first?
Most likely reason of the behavior that you have multiple instances of whatever object that contains
bool runningflag.lockwill prevent multiple threads from executing the same block of code. Most UI operations are executed on the same thread, so code will be allowed to re-enter the same block (lockis not doing anything when acquired multiple times on the same thread). In your case simpleboolflag should be enough without usinglock.