首页 > 解决方案 > 为什么会发生 System.TypeInitializationException?

问题描述

我正在尝试在 c# 中使用 WebClient 类,并且我需要它作为方法和事件侦听器,所以我在一个类中定义了它。当我尝试运行我的程序时,发生 System.TypeInitializationException,我不知道为什么。我一直在寻找解决方案,但找不到。

这是我的代码(已编辑):

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.Threading;
using System.Speech.Synthesis;
using System.Windows.Forms;
using System.Net;

class Program
{
    static WebBrowser browser1 = new WebBrowser();
    static void Main(string[] args)
    {
        //some code
        browser1.DocumentCompleted += webBrowser1_DocumentCompleted;

    }
    static void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
    {
        //some code
        Main(null);
    }

}

当我注释掉 WebBrowser 变量和任何需要它的代码时,代码工作正常。请帮助我,因为我是 C Sharp 的新手。

标签: c#

解决方案


错误说

ThreadStateException: ActiveX control '8856f961-340a-11d0-a96b-00c04fd705a2' cannot be 
instantiated because the current thread is not in a single-threaded apartment.

在 main 方法上方添加 STAThread 属性

    [STAThread]
    static void Main(string[] args)

推荐阅读