AccessViolationException in C# multithreaded form

别等时光非礼了梦想. 提交于 2019-12-11 09:29:54

问题


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.


回答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.



来源:https://stackoverflow.com/questions/21488508/accessviolationexception-in-c-sharp-multithreaded-form

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!