I just am changing a GUI application from STAThread
to MTAThread
as it does some parallel background work. Now I encountered the issue of accessing the Clipboard from within a MTAThread
application.
I tried to create a dedicated STA thread on my own, failed, then tried this class https://stackoverflow.com/a/21684059/2477582 and failed again.
From dot net framework source code I found that Application.OleRequired()
not matching ApartmentState.STA
is the only condition to raise ThreadStateException
.
But this matches for my implementation, while the exception is raised nevertheless!
Tests without VS debugger let me proceed the application from this ".NET encountered an unhandled exception" dialog and then the Clipboard contains the correct value! So it works, but I have no chance to catch the exception, as it raises from some unidentifyable thread void directly into Application.Run(new MyMainform())
.
Am I doing something wrong or has .NET behaviour changed here?
Program.cs:
[MTAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
try
{
Application.Run(new ds_Main());
}
catch (System.Threading.ThreadStateException ex)
{
// It always falls out here
System.Diagnostics.Debug.WriteLine("ThreadStateException: " + ex.ToString());
}
}
ds_Main.cs, DataGridView KeyDown handler:
private void ds_ImportTableView_KeyDown(object sender, KeyEventArgs e)
{
if (e.Control && e.KeyCode == Keys.C)
{
string ll_CopyString = "foobar"; // some other stuff is here of course...
try
{
Thread l_StaThread = new Thread(() =>
{
// this prints: STA=?STA
System.Diagnostics.Debug.WriteLine(Application.OleRequired().ToString() + "=?" + System.Threading.ApartmentState.STA.ToString());
try
{
Clipboard.SetDataObject(ll_CopyString);
}
catch (Exception ex)
{
// It never catches here ...
System.Diagnostics.Debug.WriteLine("Exception in STA Delegate: " + ex.Message);
}
});
l_StaThread.SetApartmentState(ApartmentState.STA);
l_StaThread.Start();
}
catch (Exception ex)
{
// It doesn't catch here either ...
System.Diagnostics.Debug.WriteLine("Exception in STA Thread: " + ex.ToString());
}
}
}