Saurabh Kumar
Saurabh Kumar

Reputation: 154

Multithreading: Using BeginInvoke inside lock statement ok?

Is it a good programming practice to use asynchronous operations inside a lock construct. For eg,

lock(objLocker)
{

    myDispatchder.BeginInvoke(
        System.Windows.Threading.DispatcherPriority.Render,
        new Action(() =>
                    {
                      // ..code..

                    }
}

Upvotes: 2

Views: 1202

Answers (2)

Enigmativity
Enigmativity

Reputation: 117029

Asynchronous operations within a lock does nothing except make the code more complicated for no reason and to introduce possible deadlocks.

Give your code example I can suggest that the following is probably far more useful:

myDispatchder.BeginInvoke(
    System.Windows.Threading.DispatcherPriority.Render,
    new Action(() =>
    {
        lock(objLocker)
        {
            // ..code..
        }
    }));

Upvotes: 3

Marc Gravell
Marc Gravell

Reputation: 1062550

If that is the only thing that you are protecting, then it would be redundant; there is no need to lock for BeginInvoke. Actually, it would be very harmful if that was Invoke, and the method called (the // ..code..) also tried to take a lock on objLocker - you would deadlock yourself. At the moment, it does nothing useful, and has the possibility to cause harm 3 maintenance releases down the line. In the more general case, if there was something that needed protecting, I would separate the two tasks, i.e.

lock(objLocker)
{
    // do some stuff
}
myDispatcher.BeginInvoke(...);

This then avoids any potential issues later on.

Upvotes: 7

Related Questions