Csharp/C#教程:“调用线程必须是STA,因为许多UI组件都需要这个。”WPF分享


“调用线程必须是STA,因为许多UI组件都需要这个。”WPF

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

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

在MyParticipant构造函数内部,正在构建MyVideoRenderer pic,它inheritance了VideoRenderer,VideoRenderer构造函数本身就抛出了这个exception,而没有进入构造函数。

码:

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; } ... 

我的猜测是你从后台线程创建UI元素,这是exception的原因。

读:

解决了,感谢拉法尔的post:

问题是创建新MyParticipant的线程默认设置为MTA,因此在MyParticipant中,该MTA线程正在调用新的VideoRenderer,它inheritance了一个Image。 构造UI控件的MTA线程导致此exception。

在(WPF应用程序)项目属性中,确保将启动对象设置为(未设置)。 这解决了我的问题。

上述就是C#学习教程:“调用线程必须是STA,因为许多UI组件都需要这个。”WPF分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!

www.ctvol.com true Article Csharp/C#教程:“调用线程必须是STA,因为许多UI组件都需要这个。”WPF分享

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/cdevelopment/1250993.html

(0)
上一篇 2022年11月8日 上午8:30
下一篇 2022年11月8日 上午8:33

精彩推荐