1

我遇到了 InvalidOperationException 消息“调用线程必须是 STA,因为许多 UI 组件都需要这个。” 在严重依赖引用库的 WPF 应用程序中。

我试图确定错误的来源,使用各种线程和对象的调度程序,确保 main() 具有 STAthread 属性,尝试在看似相关的方法上设置“[STAThread]”。

在 MyParticipant 构造函数内部,由于正在构造继承 VideoRenderer 的 MyVideoRenderer pic,因此 VideoRenderer 构造函数本身正在抛出此异常,而不是进入构造函数。

代码:

public class MyParticipant : Participant           //inside MainWindow.xaml.cs
    {
        public enum PictureMode
        {
            Avatar,
            Video
        }

        public PictureMode pictureMode = PictureMode.Avatar;

        public ProgressBar voiceVolume;
        public Label nameLabel;
        public MyVideoRenderer pic;
        public MyVideo video;

        public bool isCachedInClient = false;   
        public string displayName = null;
        public Image avatarImage = null;

        public static int picHeight = 480;
        public static int piclWidth = 640;
        public static int panelHeight = 155;
        public static int panelWidth = 174;

        public static Color liveColor = SystemColors.GradientActiveCaptionColor;
        public static Color nonLiveColor = SystemColors.GradientInactiveCaptionColor;


        public MyParticipant(uint objectId, VideoManager videoManager)
            : base(objectId, videoManager)
        {
            pic = new MyVideoRenderer(videoManagerRef)   
            {
                //Top = 5,
                //Left = 5,
                Height = picHeight,
                Width = piclWidth,
                //SizeMode = PictureBoxSizeMode.StretchImage
            };
...

public class VideoRenderer : System.Windows.Controls.Image         //referenced external class
{
    public VideoRenderer(VideoManagerRoot videoManager)        ///Exception here
    {
        this.videoManagerRef = videoManager;
    }
...
4

3 回答 3

8

我的猜测是您正在从后台线程创建 UI 元素,这是导致异常的原因。

读:

于 2012-07-11T19:57:04.363 回答
0

Solved, thanks to Rafal's post:

The problem is that the thread that was creating a new MyParticipant was being default set to MTA, and so inside MyParticipant, that MTA thread was calling new VideoRenderer, which inherits an Image. An MTA thread constructing a UI control results in this exception.

于 2012-07-12T14:35:49.977 回答
0

In (WPF Application) Project Properties make sure that Startup object is set to (Not Set). That solved problem in my case.

于 2018-01-23T11:06:37.893 回答