我创建了以下项目来向大家展示我打算如何做事。但是我的主要项目会更大,并且会有多个类。我只是想让它正常工作,所以我知道我在编码时采用了良好的做法。
好的,让我们开始 :),所以我的表单有一个名为“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/