multithreading in c# 2.0 and locking an object

i have a winform app in c# 2.0 .

i am reading an object's property in the main thread and changing it on a background thread.
i am using backgroundworker class.

should i lock the object before writing and reading
can anyone give me some code samples



Answer this question

multithreading in c# 2.0 and locking an object

  • onethird13

    Yes, you should lock the object if you want threadsafety.

    If you won't introduce locks then you cannot rely upon object value as it can be changed by the other thread.

    in the main and background threads you can wrap the code, where you access object properties with lock statments

    lock(myObj)

    {

    //access myObj props here

    }


  • multithreading in c# 2.0 and locking an object