Access to an object on 2 threads simultaneously

I have a C # application that owns 2 threads. One thread creates an object, while the same object is used in the second thread. Most of the time it works fine, but for a while it gives errorsObject is in use currently elsewhere.

How to make threads use the object at the same time?

thank

Edit

I am accessing an object Bitmap. One stream creates this bitmap from the stream, displaying it on PictureBox, and the second stream again converts this Bitmapto Byteand transfers it to the network.

+3
source share
4 answers

Your basic approach is a lock object (with respect to 1-1 with a shared object) and the operator lock:

MyObject shared = ...;
object locker = new object();

// thread A
lock(locker)
{
  // use 'shared'
}

// thread B
lock(locker)
{
  // use 'shared'
}

After editing

- Bitmap, , Parallel. .

, . ( ) PictureBox .

+1

, GDI - . ? , , GUI "non GUI". , , . ,

if (form.InvokeRequired)
{
    form.BeginInvoke( your operation method);
} 
else
{ 
    (same operation method);
} 
+2

Bitmap. , PictureBox, .

Bitmap InvalidOperationException. , , , , Bitmap . , a PictureBox, , , PictureBox , GUI.

+2

lock , .

:

object mylock;

lock(mylock)
{
//do someething with object
}//lock scope finishes here

mylock , .

+1

All Articles