简体   繁体   中英

checking condition fails when using threading

I am using threading in my application

I am creating a folder, when the folder is already not existing

if (!ExistingFolders.Contains(currentFolder)){
    if (lastCreatedFolder != folder) {
             lastCreatedFolder = folder;
             CreateNewFolder(context, siteLink, lName, fName);
                                }
                          }

When there are 5 threads running parallely, this condition is not working!! For example, all 5 threads are trying to create a folder named "New" first one is getting created, while the rest are throwing "Folder already exists" error as its already created

How can i check the condition in this case?

Here all 5 threads are running in parallel, and condition is true for all cases where as it should be true for only the first case

This is a race condition and you have to put a synchronisation mechanism to fix it. for example by using lock keyword you can make sure a scope of code is only accessible to one thread at a time. here lockobject is an object created before these operations. eg a readonly const is common.

lock(lockobject){

if (!ExistingFolders.Contains(currentFolder)){
    if (lastCreatedFolder != folder) {
             lastCreatedFolder = folder;
             CreateNewFolder(context, siteLink, lName, fName);
                                }
                          }
}

How can i check the condition in this case?

By using a synchronization primitive, such as a lock :

public readonly object syncRoot = new object();

lock (syncRoot)
{
    if (!ExistingFolders.Contains(currentFolder))
    {
        if (lastCreatedFolder != folder) 
        {
            lastCreatedFolder = folder;
            CreateNewFolder(context, siteLink, lName, fName);
        }
    }
}

This way, only the first thread to reach the lock statement will hold the lock, while all other threads wait for him to release it. Once it does, all others threads will see the folder has already been created.

Note that if each thread is accessing a different instance of the class containing the lock, you should make it static .

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