Corey Trager
Corey Trager

Reputation: 23141

in .NET, How do I set STAThread when I'm running a form in an additional thread?

I'm running a form in a second thread. If I do Ctrl-C to copy text on the clipboard, I get an Exception, "Current thread must be set to a single thread apartment (STA) before OLE calls can be made. (Using the clipboard involves OLE apparently).

Putting the [STAThread] with my thread proc, which is the entry point of my second thread does NOT work. What will work?

[STAThread]
private void MyFormThreadproc(object o)
{
    form = new MyForm();
    Application.Run(form);
}

Upvotes: 0

Views: 4618

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1502816

When you create the thread, call the SetApartmentState() method before you start it. You can't do this for threadpool threads.

For example:

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

Upvotes: 7

Related Questions