我在线程与类结合方面遇到问题。 对于我的问题,我编写了一个简单的代码来解释我的问题。
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;
using System.Threading;
namespace RemoteMonitorServer
{
public partial class RemoteMonitor : Form
{
Thread cThread;
Server cServer;
public RemoteMonitor()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
WriteLog("Programm started!");
cServer = new Server();
cThread = new Thread(new ThreadStart(cServer.StartServer));
cThread.IsBackground = true;
cThread.Start();
}
public void WriteLog(string sText)
{
MessageBox.Show(sText);
listBox1.Items.Add(sText);
}
}
}
该类具有以下代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace RemoteMonitorServer
{
class Server
{
public void StartServer()
{
RemoteMonitor cTest = new RemoteMonitor();
cTest.WriteLog("Thread started!");
}
}
}
现在,当我启动此代码时,列表框确实会显示“程序已启动!”但不是“线程开始!”。 虽然我收到两条 MessageBox 消息,但我相信该方法正在被调用。 Visual Studio 2010 中没有错误,有人可以告诉我我在这里做错了什么吗?
最佳答案
public delegate void RunAtFormThreadCallBack(Control control, RunningAtFormThread method);
private void RunAtFormThread(Control control, RunningAtFormThread method)
{
if (control.InvokeRequired)
{
var callback = new RunAtFormThreadCallBack(RunAtFormThread);
control.Invoke(callback, new object[] { control, method });
}
else
method.Invoke();
}
用法:
RunAtFormThread(listBox1, delegate
{
// executing at control thread...
listBox1.Items.Add(sText);
MessageBox.Show(sText);
});
关于c# - 线程跨类添加项目列表框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12467181/