简体   繁体   中英

C#: Thread safe function

which of the following code is more appropriate situation where multiple threads access the function

public ArrayList CallMe1()
    {
        ArrayList al = new ArrayList();

        lock(al.SyncRoot)
        {
            al.Add("33");
            al.Add("45");

            return al;
        }

    }

    public ArrayList CallMe2()
    {

        ArrayList al = new ArrayList();

        Monitor.Enter(al);

        al.Add("33");
        al.Add("45");
        Monitor.Exit(al);

        return al;


    }

There's no shared state in this case, so synchronisation is unnecessary.

However, assuming the arraylist was shared state, the following applies:

They're both the same ( lock implements Monitor internally ).

Mostly.

Your second version needs to release the monitor in a finally block, otherwise if the code throws an exception, the lock will never be released and will lead to deadlocks in your application.

In summary, use the first version ( lock (...) {... } ) to avoid unnecessary typing and possible mistakes.

Neither. Functions don't share any data, so no syncronisation is needed.

Neither. None of your functions have shared state (only local variables), which makes them inherently reentrant. No synchronization is required whatsoever.

As other answers have stated lock uses monitor but it does it in a better way than your second example. It's better in that it wraps calls to monitor in a try finally block ensuring that the lock is released if there is an exception.

For this reason I recommend that you use lock for nearly all operations.

1 - You don't need any lock here.

2 - Don't use Monitor if you can do it with a lock.

3 - In the first exemple, you are locking a SyncRoot object, it's better than locking on an array.

You can also find a part of the answer here .

Return statement inside (CallMe1) or outside (CallMe2) the lock makes also no difference.

the problem with .net lock is that in case of a deadlock it is not going to throw any exception or anything.

By the way you are taking lock on a newly created ArrayList every time. How is that supposed to help? I prefer creating a static object somewhere and taking a lock on that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM