ThreadStateException 发生

ThreadStateException occurred

我的程序中有两行代码似乎有问题。

ThreadStateException 出现在行 if (o.ShowDialog() == DialogResult.OK)if(s.ShowDialog() == DialogResult.OK)

程序应该解释一种编造的语言,但那部分代码还没有编造。请帮忙,我不知道该怎么做!

public class meow : Form
{
    TextBox meowbox = new TextBox();
    private string titile;
    public meow()
    {
        titile="Tiger goes Meow";
        Size = new Size(500, 600);
        Text =titile ;

        meowbox.Size = new Size(450, 520);
        meowbox.Multiline = true;
        meowbox.ScrollBars = ScrollBars.Horizontal;
        meowbox.WordWrap = true;
        meowbox.Location = new Point(25, 10);

        //file
        MenuItem feow = new MenuItem("File Meow");
        MenuItem oeow = new MenuItem("open Meow");
        MenuItem seow = new MenuItem("Save Meow");
        feow.MenuItems.Add(oeow);
        feow.MenuItems.Add(seow);
        //run
        MenuItem leow = new MenuItem("Meow");
        MenuItem ceow = new MenuItem("Check Meow");
        MenuItem reow = new MenuItem("Run Meow");
        leow.MenuItems.Add(ceow);
        leow.MenuItems.Add(reow);
        //menu
        MainMenu beow = new MainMenu();
        Menu = beow;
        beow.MenuItems.Add(feow);
        beow.MenuItems.Add(leow);
        //put it all meow
        Controls.Add(meowbox);
        //handlers
        oeow.Click += new EventHandler(oeow_Click);
        seow.Click += new EventHandler(seow_Click);
       /*ceow.Click += new EventHandler(ceow_Click);
         reow.Click += new EventHandler(reow_Click);*/
    }

    protected void oeow_Click( object sender, EventArgs e){
        Text="Oeow";
        OpenFileDialog o = new OpenFileDialog();
        if (o.ShowDialog() == DialogResult.OK)
        {
            Stream file = o.OpenFile();
            StreamReader reader = new StreamReader(file);
            char[] data = new char[file.Length];
            reader.ReadBlock(data, 0, (int)file.Length);
            meowbox.Text = new String(data);
            reader.Close();
        }
        Text = titile;
    }

    protected void seow_Click(object sender, EventArgs e)
    {
        Text="seow";
        SaveFileDialog s = new SaveFileDialog();
        if(s.ShowDialog() == DialogResult.OK)
        {
            StreamWriter writer = new StreamWriter(s.OpenFile());
            writer.Write(meowbox.Text);
            writer.Close();
        }
        Text=titile;
    }

    public static void Main()
    {
        Application.Run(new meow());
    }
}

如果您发布的代码是您的真实程序,那么问题是您没有正确设置线程的单元状态。主 Winforms UI 线程 必须 是单线程单元线程。

尝试:

[STAThread]
public static void Main()
{
    Application.Run(new meow());
}

请注意,理想情况下,您应该使用 Visual Studio 中内置的模板创建 Winforms 项目。它将为您正确配置线程。