枫城小陌 2021-10-09 13:27 采纳率: 0%
浏览 603

关于多线程访问Bitmap引起对象当前正在其他地方使用的错误提问


        Thread t1;
        Thread t2;
        int count1 = 0;
        int count2 = 0;
 
        static readonly object olock = new object();
 
        public Bitmap bitmapVal = new Bitmap(@"C:\Users\BEIYUTECH\Desktop\th.jpg");
        public Bitmap BitmapVal
        {
            get
            {
                lock (olock)
                {
                    return (Bitmap)bitmapVal.Clone(); 
                }
            }
        }
 
 
 
        private void button1_Click(object sender, EventArgs e)
        {
            t1 = new Thread(getBitmap1);
            t1.Start();
            t2 = new Thread(getBitmap2);
            t2.Start();
        }
        private void getBitmap1()
        {
            while (true)
            {
                count1++;
                this.pictureBox1.Image = this.BitmapVal;
            }
        }
 
        private void getBitmap2()
        {
            while (true)
            {
                count2++;
                this.pictureBox2.Image = this.BitmapVal;
            }
        }

出错代码行:this.pictureBox1.Image = this.BitmapVal;或者this.pictureBox2.Image = this.BitmapVal;

错误信息:

“System.InvalidOperationException”类型的未经处理的异常在 System.Drawing.dll 中发生

其他信息: 对象当前正在其他地方使用。

已经使用了lock为什么没有效果,还是说我用发错了或者其他原因。请各位大大不吝赐教!谢谢~

  • 写回答

2条回答 默认 最新

  • 於黾 2021-10-09 13:33
    关注

    对象指的是pictureBox1.Image这个对象,不是BitmapVal
    两个pictureBox是可以将Image指定为同一个Bitmap的
    -=-=-=
    问题的关键不在于对象,而在于你在子线程里操作UI对象
    想在子线程里操作UI对象,你需要使用委托。

    评论

报告相同问题?

问题事件

  • 创建了问题 10月9日

悬赏问题

  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line