Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/316.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 在Application.Run()之后更新表单_C#_Winforms - Fatal编程技术网

C# 在Application.Run()之后更新表单

C# 在Application.Run()之后更新表单,c#,winforms,C#,Winforms,这是我想做的 // pseudo code Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Form1 myForm = new Form1(); Application.Run(myForm); while(true) { string a = readline(); } form1.show(a) 换句话说,我需要表单始终显示输入。但是上面的代码将在

这是我想做的

// pseudo code
Application.EnableVisualStyles(); 
Application.SetCompatibleTextRenderingDefault(false); 
Form1 myForm = new Form1();
Application.Run(myForm); 
while(true)
{
    string a = readline();
}
form1.show(a)
换句话说,我需要表单始终显示输入。但是上面的代码将在“Application.Run(myForm);”之后停止。我没有在form1类中编写这样的代码的原因是代码的主要部分是在用F#编写的机器学习引擎上运行的,并且因为F#没有一个好的可视化设计器。因此,我尝试创建一个简单的form1.dll,并使用它来绘制随时间变化的结果。 所以我的问题是我只能初始化表单,但我不能随时间更新它。
任何提示都将不胜感激。

您试图同时做两件事,因此您的应用程序应该通过使用两个线程来反映这一点。接下来,表单的Show()方法不接受字符串,因此需要实现自己的方法

这是一个C#2.0 WinForms解决方案。程序运行线程并处理控制台输入:

static class Program
{
    [STAThread]
    private static void Main()
    {
        // Run form in separate thread
        var runner = new FormRunner();
        var thread = new Thread(runner.Start) {IsBackground = false};
        thread.Start();

        // Process console input
        while (true)
        {
            string a = Console.ReadLine();
            runner.Display(a);
            if (a.Equals("exit")) break;
        }
        runner.Stop();
    }
}
FormRunner负责线程调用:

internal class FormRunner
{
    internal Form1 form = new Form1();

    internal void Start()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(form);
    }

    private delegate void StopDelegate();

    public void Stop()
    {
        if (form.InvokeRequired)
        {
            form.Invoke(new StopDelegate(Stop));
            return;
        }
        form.Close();
    }

    private delegate void DisplayDelegate(string s);

    public void Display(string s)
    {
        if (form.InvokeRequired)
        {
            form.Invoke(new DisplayDelegate(form.Display), new[] {s});
        }
    }
}
Form1只需要显示一些内容:

    public void Display(string s)
    {
        textBox1.Multiline = true;
        textBox1.Text += s;
        textBox1.Text += Environment.NewLine;
    }

+1; 一个问题:如何确保新线程的ApartmentState是STA?不需要显式设置吗?没错,默认为MTA。您可以通过
thread.SetApartmentState(ApartmentState.STA)设置线程状态