简体   繁体   中英

Multiple Thread Access a Collection in .net

Supposed there is something like Hashtable created by Hashtable.Synchronized() which is accessed by multiple thread. and the key value pair is Guid and Object in Hashtable . One of thread need to polling this Hashtable until a specific Guid key had been added into this list by another thread.

Below is my code .

        public Hashtable syncHt = new Hashtable();
        public void Init()
        {
            Hashtable ht = new Hashtable();
            syncHt = Hashtable.Synchronized(ht);
        }

In the application initialization i will call the init();

And In one of thread I will call isExist to find the specific Guid which is added by some other thread .

public bool isExist(Guid sId)
    {
        while (true)
        {
            if (syncHt.ContainsKey(sId))
            {
                return true;
            }
        }

}

I was wondering whether this loop could be ended. How can I know the Hashtable changed during the polling ?Thanks

Take a look on concurrent collections , especially on ConcurrentBag<T>

Update

About IsExist, here is better solution

Change Hashtable on ConcurrentDictionary<Guid, object> so no lock required

Add items to repository without any lock

ConcurrentDictionary<Guid, object> repository = new ConcurrentDictionary<Guid, object>();

Check repository for existing items

    public bool IsExist(Guid id)
    {
        SpinWait.SpinUntil(() => repository.ContainsKey(id)); - you can add Timout
        return true;
    }

Here is more about SpinWait

Reading and more important assigning to a reference is always atomic in .NET.

To do atomic operation, use the System.Threading.Interlocked class. See MSDN


I was wondering whether this loop could be ended.

It will end when another (only 1 writer allowed) thread inserts the wanted value, yes.

On MSDN: Hashtable is thread safe for use by multiple reader threads and a single writing thread.

But your solution is very inefficient. The busy-loop can consume a lot of CPU time for nothing. Storing (boxed) Guids in an old style collection isn't perfect either.

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