Victor Mukherjee
Victor Mukherjee

Reputation: 11095

Scope of variable in different thread at runtime

Consider the below code:

public void MyMethod()
    {
        bool flag=true;
        BackgroundWorker worker = new BackgroundWorker();
        worker.DoWork += (x, y) =>
            {
                //time consuming task
                if (flag)
                {
                    //do something
                }
            };
        worker.RunWorkerCompleted += (x, y) =>
            {
                if (flag)
                {
                    //do something
                }
            };
        worker.RunWorkerAsync();
    }

Perhaps a stupid question, but as I can understand, after runworkerasync call, the dowork event is raised which runs its method on a different thread. Is checking the value of the local variable flag safe inside the dowork eventhandler since I feel the code exits MyMethod after calling worker.RunWorkerAsync?

Upvotes: 2

Views: 732

Answers (2)

JeffRSon
JeffRSon

Reputation: 11216

There's no problem with flag here because of a concept called Closures. However, especially with threads this can be dangerous (use your favourite search engine).

Upvotes: 4

MarcF
MarcF

Reputation: 3299

Depending on your definition of 'safe', it is possible to check the local variable flag within DoWork as it remains in scope for that method. Having said that it may not necessarily be thread safe.

Upvotes: 0

Related Questions