c# - Is that synchro-construction correct? -


i have multi-threaded application. threads use abc.connector. want 1 thread @ time have access connector property.

class abc {     /// <summary>     /// synchronization object.     /// </summary>     static object _syncobject = new object();      static dataaccess _connector;     /// <summary>     /// global object data access.     /// </summary>     public static dataaccess connector     {                 {             lock (_syncobject)             {                 return _connector.createcopy(); // copy of original _connector             }         }         set         {             lock (_syncobject)             {                 _connector = value;             }         }     } } 

is correct ?

well, make getting , setting connector property thread-safe (although i'd make _syncobject read-only). however, doesn't make dataaccess thread-safe... mutex apply while threads getting , setting property.

in other words, if 2 threads both do:

abc.dataaccess.dosomelongrunningoperation(); 

then dosomelongrunningoperation() still run concurrently 2 threads. if operation isn't thread-safe, it's still going problem.

if want 1 thread @ time use dataaccess write:

public static void useconnector(action<dataaccess> action) {     lock (_syncobject)     {         action(_connector);     } } 

then if 2 threads both do:

abc.useconnector(access => access.dolongrunningoperation()); 

then dolongrunningoperation() run in 1 thread @ time. you've still got issue misbehaving clients write:

dataaccess naughty = null; abc.useconnector(access => naughty = access); // haha! i've circumvented thread safety! naughty.dolongrunningoperation(); 

... isn't issue you.


Comments

Popular posts from this blog

c++ - Convert big endian to little endian when reading from a binary file -

C#: Application without a window or taskbar item (background app) that can still use Console.WriteLine() -

unicode - Are email addresses allowed to contain non-alphanumeric characters? -