开发者

Using Drag-and-Drop while using MTAThread

Today I came across a peculiar problem, DragDrop functions do NOT work while using MTAThread. I have searched the MSDN and I have googled various combinations of the key words.

Can anyone please explain to me why this isn't allowed? Is there a way to get around i开发者_如何转开发t?


I think you would get the following error, which might explain the reason a bit:

System.Threading.ThreadStateException: Current thread must be set to single thread apartment (STA) mode before OLE calls can be made. Ensure that your Main function has STAThreadAttribute marked on it.

Generally, use STAThread on any thread that creates UI inorder to prevent unresponsive / hanging UI. Nothing prevents you from creating a separate thread ( but STA ) for a window so that your UI is responsive:

 Thread thread = new Thread(() =>
  {
     Window1 w = new Window1();
     w.Show();

     System.Windows.Threading.Dispatcher.Run();
  });



  thread.SetApartmentState(ApartmentState.STA);
  thread.Start();

There can be worker threads which can be MTA. The worker thread(s) can interact with the UI thread by passing messages to the Dispatcher ( in case of WPF)

Have a look at this blog post, old, but provides lots of information on Apartments and Pumping

Apartments and Pumping in the CLR

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜