Reputation: 4167
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.
Upvotes: 3
Views: 3401
Reputation: 273229
Your basic approach would be a locking object (in a 1-1 relation with the shared object) and a lock
statement:
MyObject shared = ...;
object locker = new object();
// thread A
lock(locker)
{
// use 'shared'
}
// thread B
lock(locker)
{
// use 'shared'
}
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.
Upvotes: 2
Reputation: 4381
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
Accessing Bitmap
object from several thread would not cause InvalidOperationException
. It could break your your data if you write and read the same instance concurrently, but as far as I can tell Bitmap
does not impose a specific threading model. On the other hand a PictureBox
does, so I suspect you are trying to either read or write back to PictureBox
instance from a non-GUI worker thread.
Upvotes: 2
Reputation: 1847
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
if (form.InvokeRequired)
{
form.BeginInvoke( your operation method);
}
else
{
(same operation method);
}
Upvotes: 2
Reputation: 63190
You need to lock
this variable each time it is used by either one of the threads.
As such:
object mylock;
lock(mylock)
{
//do someething with object
}//lock scope finishes here
where mylock
is used by each lock that accesses this particular variable.
Upvotes: 1