Search code examples
c#eventslockingvolatileraw-input

About lock on touch event in C#


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?


Solution

  • Most likely reason of the behavior that you have multiple instances of whatever object that contains bool running flag.

    lock will 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 (lock is not doing anything when acquired multiple times on the same thread). In your case simple bool flag should be enough without using lock.