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..
}
}
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.
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..
}
}));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With