.NET – Why Windows Clipboard Requires an STA Thread

netwindows

To copy something to the clipboard in Windows (at least in .NET as far as I know) it has to be done on a separate thread that is in STA Mode. One example I have used is this.

Thread thread = new Thread(() => Clipboard.SetText(s.Trim()));
thread.SetApartmentState(ApartmentState.STA); //Set the thread to STA
thread.Start();
thread.Join();

Why do I have to do all of that instead of being able to just call:

Clipboard.SetText("text")

Best Answer

In a word, legacy.

In the article Why is STAThread required?, we're told:

When the STAThreadAttribute is applied, it changes the apartment state of the current thread to be single threaded. Without getting into a huge discussion about COM and threading, this attribute ensures the communication mechanism between the current thread and other threads that may want to talk to it via COM. When you're using Windows Forms, depending on the feature you're using, it may be using COM interop in order to communicate with operating system components. Good examples of this are the Clipboard and the File Dialogs.

Said another way, communication with operating system components like the Clipboard are handled through COM and that requires changing the apartment state of the thread by using an STA thread.

Related Topic