C#0x80131520错误,单线程单元(STA)模式

2023-12-01  本文已影响0人  大龙10

1、C#报错

HResult=0x80131520
Message=在可以调用 OLE 之前,必须将当前线程设置为单线程单元(STA)模式。请确保您的 Main 函数带有 STAThreadAttribute 标记。 只有将调试程序附加到该进程才会引发此异常。

2、分析

[STAThread] attribute指示应用程序的 COM 线程模型是单线程单元
而于此对应的多线程单元则是 [MTAThread] (多线程单元线程)

这是一种线程模型,用在程序的入口方法上(在C#和VB.NET里是Main()方法),如果设置了[MTAThread] ,那么在调用如FolderBrowserDialog时就会出现错误,
解决方法:额外开启一个新的线程,将新线程单元状态设置为(STA)单线程单元。

3、解决方法

           System.Threading.Thread s = new System.Threading.Thread(new System.Threading.ThreadStart(() =>
            {
                OpenFileDialog openFileDialog = new OpenFileDialog();
                openFileDialog.Title = "选择操作的图片";
                openFileDialog.Filter = "图片 *.jpg|*.jpg|*.bmp|*.bmp|图像*.png|*.png";
                if (openFileDialog.ShowDialog() == DialogResult.OK)
                {
                    filePath = openFileDialog.FileName;
                    image = Image.FromFile(filePath);
                    src_img = Cv2.ImRead(filePath);
                    Mat tem1 = new Mat();
                    src_img.CopyTo(tem1);
                    if (reList.Count > 0)
                    {
                        reList[0] = tem1;
                    }
                    else
                    {
                        reList.Add(tem1);
                    }
                }
                if (filePath != "")
                {
                    skinPictureBox_Pic0.Image = image;
                }
            }));
            s.SetApartmentState(System.Threading.ApartmentState.STA);
            s.Start();

4、参考资料

 [lixy579]的博客:
https://blog.csdn.net/qq_42789677/article/details/113716364
上一篇 下一篇

猜你喜欢

热点阅读