我有一个 C# Windows 应用程序,Form1 上有一个按钮,当按下它时会运行一个很长的程序。在程序运行时,我希望用户界面可用,因此我会将大部分代码放入单独的线程中。作为测试,我将代码放入一个线程并查看它是否有任何问题。我有2个问题。我的最终愿望是让 UI 正常工作,所以如果这不是启动新线程的最佳方式,请告诉我。
首先,虽然程序已编译,但我创建的线程并没有从主线程中看到变量中的所有值。大多数字符串是空的,int 和 float 值为 0。在线程中保持其值的唯一变量是那些使用值创建然后从不更改的变量。显然,我应该能够看到所有变量中的所有值。
其次,我在表单上添加了一个文本框,以便我可以提供有关长时间运行的程序的信息。文本框显示来自主线程的信息没有问题,但我创建的线程中没有显示任何内容。我希望 Form1 上的文本框也可以从线程中更新。
我在 Windows XP 上使用 Visual Studio 2008。
这些是变量的定义。它们位于应用程序的 Program.cs 部分。
partial class Form1
{
string TBI_File = "";
int junk = 27;
string junkstr = "Two out of three ain\'t bad";
double RADD;
string PROGRAMMER = "Don and Jim";
float currentSize = 8.25F;
float sizechange = 10.0F;
}
在主线程中(按下按钮后)我创建了新线程。我从http://msdn.microsoft.com/en-us/library/aa645740(v=vs.71).aspx复制并修改了这段代码 我评论了 Abort 和 Join 因为在测试的这一点上我想要线程tro 继续运行,直到我单独停止它。
Wprintf("Alpha.Beta starting");
Alpha oAlpha = new Alpha();
// Create the thread object, passing in the Alpha.Beta method
// via a ThreadStart delegate. This does not start the thread.
Thread oThread = new Thread(new ThreadStart(oAlpha.Beta));
// Start the thread
oThread.Start();
// Spin for a while waiting for the started thread to become
// alive:
while (!oThread.IsAlive) ;
// Put the Main thread to sleep for 1 millisecond to allow oThread
// to do some work:
//original
//Thread.Sleep(1);
Thread.Sleep(10);
// Request that oThread be stopped
//oThread.Abort();
// Wait until oThread finishes. Join also has overloads
// that take a millisecond interval or a TimeSpan object.
//oThread.Join();
Wprintf("Alpha.Beta has finished");
下面是线程运行的代码。
public class Alpha : Form1
{
// This method that will be called when the thread is started
public void Beta()
{
while (true)
{
//Console.WriteLine("Alpha.Beta is running in its own thread.");
Wprintf("Alpha.Beta is running in its own thread. " +
" RADD: " + RADD +
" CurrentSize: " + currentSize.ToString() +
" TBI_File: " + TBI_File +
" PROGRAMMER: " + PROGRAMMER +
" sizechange: " + sizechange.ToString() +
" junk: " + junk +
" junkstr: " + junkstr);
textBox1.AppendText("Alpha.Beta is running in its own thread.");
}
}
};
Wprintf 将该消息附加到日志文件并将消息添加到文本框。它适用于整个程序,除了附加到文本框的末尾不适用于创建的线程。我添加了上面的 TextBox1.AppendText(在线程中)以尝试使其工作,但它没有做任何事情,并且线程的文本框中没有显示任何消息。
日志文件的部分如下。日志文件是从线程中附加的,所以我可以看到线程中变量的值(我还查看了调试器中的变量并得到了相同的值)更改的变量是 RADD 和 TBI_FILE,你可以在下面看到RADD 是 0.0 并且 TBI_File 是 '' 在线程中。其他的在程序中没有改变,只是得到了声明时设置的值。
Alpha.Beta is running in its own thread. RADD: 0 CurrentSize: 8.25 TBI_File: PROGRAMMER: Don and Jim sizechange: 10 junk: 27 junkstr: Two out of three ain't bad
我在这里询问了这个问题的早期版本:程序运行时 C# 程序的初始形式不可用
正如我之前指出的,我需要让 UI(文本框并单击 X 退出)可用,所以如果这不是一个好方法,请告诉我。
谢谢,