Pergunta

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.

Foi útil?

Solução

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.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top