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.
Object 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.
Bitmap
PictureBox
Byte
Your basic approach is a lock object (with respect to 1-1 with a shared object) and the operator lock:
lock
MyObject shared = ...; object locker = new object(); // thread A lock(locker) { // use 'shared' } // thread B lock(locker) { // use 'shared' }
- Bitmap, , Parallel. .
, . ( ) PictureBox .
, GDI - . ? , , GUI "non GUI". , , . ,
if (form.InvokeRequired) { form.BeginInvoke( your operation method); } else { (same operation method); }
Bitmap. , PictureBox, .
Bitmap InvalidOperationException. , , , , Bitmap . , a PictureBox, , , PictureBox , GUI.
InvalidOperationException
lock , .
:
object mylock; lock(mylock) { //do someething with object }//lock scope finishes here
mylock , .
mylock