I have an c# application which owns 2 threads. One thread is creating an object while the same object is being used in the second thread. Most of the time it works fine but some time it gives and error Object is in use currently elsewhere.
How to make it possible for threads to use object at same time?
Thanks
Edit
I am accessing a Bitmap
object. One thread is creating this bitmap from a stream, displaying it on PictureBox
and the second thread is again converting this Bitmap
to Byte
and transmitting it on the network.
The language of the error message makes it sound like it's coming from the GDI subsystem or something similar. Is this a GUI application? If yes, the most likely cause is that you are accessing GUI elements from a "non GUI" thread. For the uninitiated, all operations on any GUI control, like a form or button must be sent to it through it's message pump. You can do that by roughly doing
You need to
lock
this variable each time it is used by either one of the threads.As such:
where
mylock
is used by each lock that accesses this particular variable.Your basic approach would be a locking object (in a 1-1 relation with the shared object) and a
lock
statement:After the Edit
If you are converting the Bitmap in any way it is probably better to forget about Parallel. It is a complicated class with its own internal locking.
If you don't convert, then don't use the bitmap. It will be easier (not trivial) to fork the incoming stream for PictureBox and outgoing stream.
Accessing
Bitmap
object from several thread would not causeInvalidOperationException
. It could break your your data if you write and read the same instance concurrently, but as far as I can tellBitmap
does not impose a specific threading model. On the other hand aPictureBox
does, so I suspect you are trying to either read or write back toPictureBox
instance from a non-GUI worker thread.