Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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..

                    }
}
like image 798
Saurabh Kumar Avatar asked Nov 23 '25 02:11

Saurabh Kumar


2 Answers

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.

like image 167
Marc Gravell Avatar answered Nov 25 '25 15:11

Marc Gravell


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..
        }
    }));
like image 41
Enigmativity Avatar answered Nov 25 '25 15:11

Enigmativity



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!