views:

1174

answers:

3

Hello, I am writing a WinForms application in C#.

At one point in the application, I spawn a new STA thread (create thread, then SetApartmentState) that creates a new form and then shows it with plain old Show(). The form itself contains only a docked DataGrid whose DataSource points to a DataTable retrieved from a newly open SqlConnection. All data and UI objects are created on the same thread.

When I execute that code I get a LoaderLock exception with the following (helpful) text:

Attempting managed execution inside OS Loader lock. Do not attempt to run managed code inside a DllMain or image initialization function since doing so can cause the application to hang.

I'm doing no such thing, at least not intentionally! The stack trace has only unmanaged code at the head and I'm unable to debug that with C# Express 2008.

Looking around the Internets, people usually just disable that exception within VisualStudio. Is this another case of Microsoft being padantic, or should I actually spend time figuring out what's going on?

Update The error seemed to be caused by opening multiple forms (each with data grid, etc.) rapidly. If I switch the Show() to ShowDialog() and view the forms one at a time, then the error goes away.

+3  A: 

I've seen this before when using P/Invoke with a DLL which wasn't built quite right. I think we ascertained that it wasn't dangerous in our particular case and would take more effort to fix than to disable the warning.

Do you have any native code in your app?

Jon Skeet
We've had this warning as well. It caused rare hangs in the debugger - but no other problem that we've seen.
configurator
No native code at all. Hopefully, once I get back to the office I'll be able to track down the unmanaged call stack.
Frank Krueger
+1  A: 

I've had this exact problem before now with multi-threading C# forms. It was a while back so I'm struggling to remember the details, but I recall the issue was related to performing operations on forms or controls by a thread which doesn't own them -- E.g. calling Show() from the wrong thread. If you pass a message to the owning thread and get it to handle such operations then that might solve your problem.

Nik
I'm very careful about my multithreading. In this case, the thread does not communicate at all with other threads so I am pretty confident that cross thread communication is not the issue here.
Frank Krueger
+2  A: 

I've experienced this when working with Managed DirectX. My solution was to disable the Loader Lock debugging assistant, although this might not be the best solution for every case. It certainly was not a problem with production code.

Charlie Salts