c# - checking condition fails when using threading -
i using threading in application
i creating folder, when folder not existing
if (!existingfolders.contains(currentfolder)){ if (lastcreatedfolder != folder) { lastcreatedfolder = folder; createnewfolder(context, sitelink, lname, fname); } }
when there 5 threads running parallely, condition not working!! example, 5 threads trying create folder named "new" first 1 getting created, while rest throwing "folder exists" error created
how can check condition in case?
here 5 threads running in parallel, , condition true cases should true first case
this race condition , have put synchronisation mechanism fix it. example using lock keyword can make sure scope of code accessible 1 thread @ time. here lockobject object created before these operations. e.g. readonly const common.
lock(lockobject){ if (!existingfolders.contains(currentfolder)){ if (lastcreatedfolder != folder) { lastcreatedfolder = folder; createnewfolder(context, sitelink, lname, fname); } } }
Comments
Post a Comment