Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I pass a lock object by reference?

I have a recursive function that spawns several async tasks. Each task updates a common dictionary object.

Is it OK for me to share the lock object with the other threads as a parameter in the function?

public class RecursiveTest
{ 

   void DoRecursiveWork(ref object myDictLock, dictionary<string,string> myDict)
   {
    // yadda.. async code that calls DoRecursiveWork()

   }

}
like image 823
makerofthings7 Avatar asked Oct 15 '25 05:10

makerofthings7


1 Answers

Assuming that you are planning to do something like this

// do something
lock (myDictLock) {
    // access the dictionary
}
// do something else

you can pass your object "by reference" or by "value" (that is, by reference to the reference or by value of the reference, because object is a reference type). In both cases locking on the object is going to work. When you pass by reference, you'll be able to assign the variable passed at the top of the recursive chain, too, although I doubt that that is what you are planning to do.

like image 196
Sergey Kalinichenko Avatar answered Oct 17 '25 17:10

Sergey Kalinichenko



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!