Accessing an object on 2 threads at the same time

2020-07-23 03:09发布

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.

4条回答
够拽才男人
2楼-- · 2020-07-23 03:49

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);
} 
查看更多
Explosion°爆炸
3楼-- · 2020-07-23 03:54

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.

查看更多
相关推荐>>
4楼-- · 2020-07-23 03:59

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'
}

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.

查看更多
forever°为你锁心
5楼-- · 2020-07-23 03:59

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.

查看更多
登录 后发表回答