0

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

结构fe如下:
我从服务引用中接收到一些驱动数据(命名空间:ServiceReference.Driver)
我的项目中驱动数据的命名空间是'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?

谢谢。

4

1 回答 1

1

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

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

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

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

So, you will need to ensure that you are creating your user control from the main thread. the easiest way to do this: If you already have access to the form/window that the user control is going to be placed on, just use:

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.  

You will need to do the same thing any time an incoming call from your web service needs to update a property on the control (of course, then you could use the Dispatcher instance that is associated with the control).

This is all based on the assumption that you are responding to an incoming wcf call. (sorry if I took you off track).

于 2013-07-25T13:27:20.423 回答