1

First off this is my first C# project. I have been working on this project for about 6 months.

We have a winforms program and it contains a logging GUI. In order to keep the rest of the program responsive I wanted to create the logging gui on a separate thread since it can be quite intensive when lots of stuff is going on.

This is how I attempted to open the the form on a new GUI thread. In general it works and keeps the main gui responsive. However we now randomly get a AccessViolationException (http://pastebin.com/7tLtBSei) when this is activated and I am at a loss.

var thread = new Thread(() =>
{
    loggingForm = new LoggingForm(Logger.path);
    Application.Run(loggingForm);
});
thread.Name = "LoggingFormGUIThread";
thread.Start();

The logging GUI just batch reads the log file and appends it to a RichTextBox. It doesn't touch any managed code.

DrWu
  • 574
  • 5
  • 10

1 Answers1

1

You need to set the apartment state of the thread to STA.

thread.SetApartmentState(ApartmentState.STA);
thread.Name = "LoggingFormGUIThread";
thread.Start();

This is required for many user interface components (such as RichTextBox) to function correctly.

Reed Copsey
  • 554,122
  • 78
  • 1,158
  • 1,373
  • Thanks for a quick and helpful answer. This seems to have fixed the issue. I haven't quite wrapped my head around why this is needed yet though. – DrWu Jan 31 '14 at 20:01
  • @DrWu Many UI elements use COM underneath, and this is required for the COM objects to function properly. In general, you need to always make UI threads STA. – Reed Copsey Jan 31 '14 at 20:02
  • I found an explanation why here http://stackoverflow.com/questions/4154429/apartmentstate-for-dummies Thanks again. – DrWu Jan 31 '14 at 20:21