简体   繁体   English

C#多线程形式的AccessViolationException

[英]AccessViolationException in C# multithreaded form

First off this is my first C# project. 首先,这是我的第一个C#项目。 I have been working on this project for about 6 months. 我已经在这个项目上工作了大约6个月。

We have a winforms program and it contains a logging GUI. 我们有一个winforms程序,它包含一个日志记录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. 为了使程序的其余部分保持响应,我想在一个单独的线程上创建日志记录gui,因为在进行大量操作时它可能会非常密集。

This is how I attempted to open the the form on a new GUI thread. 这就是我尝试在新的GUI线程上打开表单的方式。 In general it works and keeps the main gui responsive. 通常,它可以正常工作并保持主GUI的响应速度。 However we now randomly get a AccessViolationException ( http://pastebin.com/7tLtBSei ) when this is activated and I am at a loss. 但是,当激活它时,我们现在随机获得一个AccessViolationException( http://pastebin.com/7tLtBSei ),我很茫然。

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. 日志记录GUI只是批量读取日志文件,并将其附加到RichTextBox。 It doesn't touch any managed code. 它不涉及任何托管代码。

You need to set the apartment state of the thread to STA. 您需要将线程的单元状态设置为STA。

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

This is required for many user interface components (such as RichTextBox ) to function correctly. 这是许多用户界面组件(例如RichTextBox )正常运行所必需的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM