同时访问 2 个线程上的对象 [英] Accessing an object on 2 threads at the same time
问题描述
我有一个拥有 2 个线程的 c# 应用程序.一个线程正在创建一个对象,而第二个线程正在使用同一个对象.大多数情况下它工作正常,但有时它会给出错误 Object is in using current别处.
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?
谢谢
编辑
我正在访问一个 Bitmap
对象.一个线程从流中创建这个位图,将它显示在 PictureBox
上,第二个线程再次将这个 Bitmap
转换为 Byte
并将其传输网络.
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.
推荐答案
您的基本方法是锁定对象(与共享对象处于 1-1 关系)和 lock
语句:
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.
如果不转换,就不要使用位图.为 PictureBox 和传出流分叉传入流会更容易(并非微不足道).
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.
这篇关于同时访问 2 个线程上的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!