some_name
some_name

Reputation: 1193

New thread inside lock - c#

I need to lock an object (collection), do some operations and call a function that opens a thread using ThreadPool (inside the same lock block).

My question, are the operations performed inside the new thread will still considered thread safe?

Upvotes: 1

Views: 1834

Answers (3)

ash
ash

Reputation: 21

Please take a look at my post here:

http://pilpag.blogspot.dk/2016/04/advanced-programming-easy-way-to-manage.html

In short, use this code:

public class LockContainer
{
    private BlockingCollection<object> lockItems { get; set; }

    private object LocalLockItem { get; set; }

    public LockContainer()
    {
        lockItems = new BlockingCollection<object>();
        LocalLockItem = new object();
    }

    public object GetLockItem(string str)
    {
        lock (LocalLockItem)
        {
            if (!lockItems.Any(li => (string)li == str))
            {
                lockItems.Add(str);
            }
            return lockItems.First(li => (string)li == str);
        }
    }
}

Upvotes: 1

Andy
Andy

Reputation: 3743

You are likely to release the lock before the thread finishes its job, unless you wait for it to exit.

lock(collection){
  DoSomeWork();
  LaunchNewThread(); =>  newThread starts
} => the lock will likely be released BEFORE newThread ends

So you must wait for newThread to finish before releasing the lock. The ideal solution would be to do everything( the locking and DoSomeWork) inside newThread. If that's not possible, you can create another thread that locks, and waits fot newThread to end:

anotherThread{
    lock(collection){
      DoSomeWork();
      LaunchNewThread();
      newThread.JOIN(); => execution will stop until newThread finishes
    } => the lock will be released AFTER newThread returns
}

Upvotes: 3

Jon
Jon

Reputation: 437604

No. The new thread's code runs in its own context, and the lock statement (which is really just a convenient way to call Monitor.Enter) operates on a per-thread basis.

Upvotes: 4

Related Questions