【问题标题】:WCF (WPF) error: calling thread must be STAWCF (WPF) 错误:调用线程必须是 STA
【发布时间】:2013-07-25 13:08:42
【问题描述】:

我从服务参考收到一些数据。

结构 f.e.如下:
我从服务引用中收到了一些驱动程序数据(命名空间:ServiceReference.Driver)
我的项目中 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);
    }

但是当我到达这里时:

public DriverUserControl(Driver magnet)
    {
        InitializeComponent();

        this.magnet = magnet;
        Render();
    }

每当它到达用户控件的构造函数时,就会出现以下错误“调用线程必须是 STA,因为许多 UI 组件都需要这个”。

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

谢谢。

【问题讨论】:

  • 为什么要在Driver 类中创建用户控件?
  • Driver 对象在哪里创建? ServiceReference 在这一切中的作用是什么?不清楚。
  • Driver 构造函数在哪个线程上被调用?你需要调试它看它是否是主线程,它的ApartmentState是否是STA,否则你必须手动创建一个STA线程。

标签: wpf multithreading wcf sta


【解决方案1】:

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

通常,WPF 或 winform 应用程序的主线程已经是 STA(如果您搜索它,您会在代码生成的文件中找到应用于 Main 方法的 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 调用的假设。 (对不起,如果我让你偏离了轨道)。

【讨论】:

  • 是的,没错。驱动程序在 WCF 服务的回调上实例化。我正在尝试这个,如果它已修复,我会告诉你:) thx
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-01-05
  • 1970-01-01
相关资源
最近更新 更多