Farid Fereidooni
Farid Fereidooni

Reputation: 131

Reseting ManualResetEvent just after WaitOne is called

Imagine this scenario when there is a button on windows form that reads value of a variable called x. Meanwhile there is a thread that runs once in a while ( using a timer) that clears that variable and puts new data in it:

        //this function runs by a thread
    void newData()
    {
        manualReset.WaitOne();
        //clear x
        //put new data in it
    }
    private void btRead_Click(object sender, EventArgs e)
    {
        manualReset.Reset();
        //read x
        ManualReset.Set();
    }

now if I click the button just in time when the thread executes the line "waitOne()", resetting won't take any effect this time because "waitOne" has passed and the thread will clear the data while I'm trying to read it in the main UI thread. So whats the solution? Thanks in advance

Upvotes: 0

Views: 34

Answers (1)

Idle_Mind
Idle_Mind

Reputation: 39132

Use the lock statement:

The lock keyword ensures that one thread does not enter a critical section of code while another thread is in the critical section. If another thread tries to enter a locked code, it will wait, block, until the object is released.

    private Object objLockVar = new Object();

    void newData()
    {
        // ...code...

        lock (objLockVar)
        {
            //clear x
            //put new data in it
            // other code considered part of the "atomic" operation
        }


        // ...more code...
    }

    private void btRead_Click(object sender, EventArgs e)
    {
        lock (objLockVar)
        {
            // read x
        }

        // ...more code...
    }

Upvotes: 3

Related Questions