Pregunta

I receive some data from a service reference.

The structure f.e. is as follows:
I receive some driverdata from the service reference (namespace: ServiceReference.Driver)
The namespace of the driverdata in my project is 'MyProject.Driver'.

DriverUserControl should be created in the constructor of 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);
    }

But when i get here:

public DriverUserControl(Driver magnet)
    {
        InitializeComponent();

        this.magnet = magnet;
        Render();
    }

Whenever it reaches the constructor of the usercontrol the following error "The calling thread must be STA, because many UI components require this" shows up.

Because I never started a thread anywhere in my project I don't know how I should set this to STA. I guess the servicereference is seen as a thread, but still, is there a way to change this to STA?

Thanks.

¿Fue útil?

Solución

How does your control get instantiated? Is it created when the program starts, or are you listening for a call coming in from a WCF service?

Normally, the main thread for a WPF or winform app is already STA ( you will find the STAThreadAttribute applied to the Main method in a code generated file, if you search for it)

So I suspect that you are instancing your control in response to an incoming wcf call. Is that right?

If that's the case, you have an additional concern: All UI windows in Windows have thread affinity, which means that only the thread that created them is allowed to talk to them. Typically this is ensured by only creating windows or controls from the main thread. So background threads should not be directly touching members of a UI control.

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).

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top