WCF(WPF)错误:调用线程必须是STA

WCF(WPF)错误:调用线程必须是STA,wpf,multithreading,wcf,sta,Wpf,Multithreading,Wcf,Sta,我从服务引用中收到一些数据 结构f.e.如下所示: 我从服务引用(命名空间:ServiceReference.Driver)接收到一些driverdata 我的项目中driverdata的命名空间为“MyProject.Driver” DriverUserControl应在MyProject.Driver的构造函数中创建 public Driver(int id, string name, string telephone, string plate, Dic

我从服务引用中收到一些数据

结构f.e.如下所示:
我从服务引用(命名空间:ServiceReference.Driver)接收到一些driverdata
我的项目中driverdata的命名空间为“MyProject.Driver”

DriverUserControl应在MyProject.Driver的构造函数中创建

public Driver(int id, string name, string telephone, string plate,
                  Dictionary<DateTime, TransportType> transportTypes, Division division)
    {
        this.id = id;
        this.name = name;
        this.telephone = telephone;
        this.plate = plate;
        this.transportTypes = transportTypes;
        this.division = division;
        userControl = new DriverUserControl(this);
    }
每当它到达usercontrol的构造函数时,就会出现以下错误:“调用线程必须是STA,因为许多UI组件都需要它”

因为我从来没有在我的项目中的任何地方启动过线程,我不知道该如何将其设置为STA。我猜servicereference被视为一个线程,但仍然有办法将其更改为STA吗


谢谢。

您的控件是如何实例化的?它是在程序启动时创建的,还是您正在侦听来自WCF服务的呼叫

通常,WPF或winform应用程序的主线程已经是STA(如果搜索,您将在代码生成的文件中找到应用于主方法的STAThreadAttribute)

因此,我怀疑您正在实例化控件以响应传入的wcf调用。是这样吗

如果是这种情况,您还有一个问题:windows中的所有UI窗口都有线程关联,这意味着只有创建它们的线程才允许与它们对话。通常,仅通过从主线程创建窗口或控件来确保这一点。所以后台线程不应该直接接触UI控件的成员

因此,您需要确保从主线程创建用户控件。最简单的方法是: 如果您已经有权访问要放置用户控件的窗体/窗口,只需使用:

TheWindowHostingTheControl.Dispatcher.Invoke (or BeginInvoke, or one of the AsyncInvokes), passing in a delegate to the code that instances your control.  that will cause the control to be created on the same thread that the host window has affinity for.  
每当来自web服务的传入调用需要更新控件上的属性时,您都需要执行相同的操作(当然,您可以使用与控件关联的Dispatcher实例)


这都是基于您正在响应传入wcf呼叫的假设。(如果我让您偏离轨道,很抱歉)。

为什么要在
Driver
类中创建Usercontrol?在哪里创建
Driver
对象?ServiceReference在这一切中扮演什么角色?不清楚。在哪个线程上调用驱动程序构造函数?你需要调试它,看看它是否是主线程,它的ApartmentState是否是STA,否则,你必须手动创建一个STA线程。是的,可能是重复的。在WCF服务的回调上实例化驱动程序。我正在尝试这一点,我让你知道,如果它是固定的:)thx
TheWindowHostingTheControl.Dispatcher.Invoke (or BeginInvoke, or one of the AsyncInvokes), passing in a delegate to the code that instances your control.  that will cause the control to be created on the same thread that the host window has affinity for.