Search code examples
multithreadingelementhoststa

ElementHost gives me "The calling thread must be STA, because many UI components require this."


I just added an ElementHost to a windows Form(There are some other c# code in the Form). Then it gave me the error "The calling thread must be STA, because many UI components require this." I changed the thread to STA, but it blocked other things...is there anyway to make the elementhost work without touching any other code?

here is the code how i change thread:

public UCClientSummary()
    {
        InitializeComponent();

        Thread thread = new Thread(createElementHost);
        thread.SetApartmentState(ApartmentState.STA);
        thread.Start();
        thread.Join();


    }

    public void createElementHost()
    {
        ElementHost elementHost = new ElementHost();
        elementHost.Dock = DockStyle.Fill;
        LDControls.ucCell uc = new LDControls.ucCell();
        elementHost.Child = uc;
        this.Controls.Add(elementHost);
    }

Solution

  • Add the [STAThread] attrribute in front of your main. I am not sure if switching thread apartment state in between works.

    It may be that the background workers are already created in the wrong apartment state.

    hth

    Mario