C# 多线程多类 gui 应用程序,我这样做对吗?

标签 c# multithreading class user-interface

我创建了以下项目来向大家展示我打算如何做事。但是我的主要项目会更大,并且会有多个类。我只是想让它正常工作,所以我知道我在编码时采用了良好的做法。

好的,让我们开始 :),所以我的表单有一个名为“button1”的按钮和一个名为“textBox1”的文本框,我有一个名为“Class1”的类,它有一个方法“testtest()”,我只是把Thread.Sleep 在 testtest 方法中,这样我就可以发现它在另一个线程上运行。

这是我的表单代码

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace Test
{
  public partial class Form1 : Form
  {
    public Form1()
    {
      InitializeComponent();
    }

    delegate void Class1Deligate();

    private void button1_Click(object sender, EventArgs e)
    {
      Class1 c = new Class1();
      Class1Deligate testMethod = new Class1Deligate(c.testtest);
      testMethod.BeginInvoke(endTestMethod, testMethod);
    }

    void endTestMethod(IAsyncResult ar)
    {

    }
  }
}

这是我的一级代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace Test
{
  class Class1
  {
    public void testtest()
    {
      Thread.Sleep(8888);
      MessageBox.Show("Done");
    }
  }
}

我是否正确地创建了一个新线程?有人可以告诉我如何在运行时从 class1 中的 testtest 方法更新 textbox1 吗?我发了一篇较早的帖子,有人告诉我使用 Dispatcher,但由于某种原因,Dispatcher 类似乎对我不可用。

最佳答案

我不认为你真的开始了一个话题。 delegate.BeginInvoke 可能使用内部 ThreadPool 来完成它的投标。作为旁注,我认为您不应该调用 BeginInvoke 之后没有适当的 EndInvoke 调用(否则对 IAsyncResult 的引用从 BeginInvoke 调用返回的值不会被释放)。

如果您想要一个新线程,您可以使用 Thread 创建一个新线程类。

Thread t = new Thread(c.testtest);
t.IsBackground = true; // end if main thread ends
t.Start();

请注意,如果您像上面那样使用 Thread 类,并且使用 GUI,则需要将方法附加到 GUI 线程以更新它。您可以使用 Control.Invoke 调用来做到这一点

public void updateGUI(object state) {
    if (control.InvokeRequired) {
        control.Invoke(new Action<object>(updateGUI), state);
        return;
    }
    // if we are here, we can safely update the GUI
}

关于C# 多线程多类 gui 应用程序,我这样做对吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4061578/

相关文章:

multithreading - 带有 OpenMP 的 OpenGL 总是出现段错误

multithreading - C++11 中的动态内存分配是线程安全的吗?

c++ - 使用 default_random_engine 作为类成员并且没有类会导致不同的数字(相同的种子)

c# - Windows Phone 8.0 证书固定

c# - 如何在 Fluent NHibernate 中从数据库 char 数据类型中修剪字符串属性数据类型

c# - 使用 View 寻呼机在 fragment 中选择的选项卡上重新加载数据

multithreading - 是否有适用于 Android 的稳定 native 线程 API?

c++ - 如何在 C++ 类中使用自引用类型和别名

ios - 从另一个类访问 UIButton 不起作用?

c# - 'DelegatingHandler' 列表无效,因为 'InnerHandler' 的属性 'handler' 不为空