WinForm是主窗体,
public class WinForm: Form
{
public WinServer()
{
InitializeComponent();
}
private void WinServer_Load(object sender, EventArgs e)
{
Receive.Instance.Start();
}
}
还有一个类Receive
public class Receive
{
static Receive_instance = null;
public static Receive Instance
{
get
{
if (null == _instance)
{
_instance = new Receive();
}
return _instance;
}
}
public void Start()
{
try
{
Thread th = new Thread(refresh);
th.IsBackground = true;
th.Start();
}
catch(Exception ex)
{
}
}
void refresh()
{
while (true)
{
//在这里更新TextBox的内容
}
}
}
这个是我的类 ,具体要怎么写?
textbox_delegate dt = new textbox_delegate(msg);
“msg”是“变量”,但此处被当做“方法”来使用
textbox_delegate dt = new textbox_delegate(textbox);
你需要知道Control.InvokeRequired的用法。这个与线程操作有关。参考一个代码示例:
在你的WinForm里定义如下的一个函数:
private void SetText(string text)在线程里如下调用这个函数:
// This event handler creates a thread that calls a在应用程序中实现多线程的首选方式是使用 BackgroundWorker 组件。 BackgroundWorker 组件使用事件驱动模型实现多线程。 后台线程运行 DoWork 事件处理程序,而创建控件的线程运行 ProgressChanged 和 RunWorkerCompleted 事件处理程序。 可以从 ProgressChanged 和 RunWorkerCompleted 事件处理程序调用控件。
使用 BackgroundWorker 进行线程安全调用
创建一个方法,该方法用于执行您希望在后台线程中完成的工作。 不要调用由此方法中的主线程创建的控件。
创建一个方法,用于在后台工作完成后报告结果。 在此方法中可以调用主线程创建的控件。
将步骤 1 中创建的方法绑定到 BackgroundWorker 的实例的 DoWork 事件,并将步骤 2 中创建的方法绑定到同一实例的 RunWorkerCompleted 事件。
若要启动后台线程,请调用 BackgroundWorker 实例的 RunWorkerAsync 方法。
在下面的代码示例中,DoWork 事件处理程序使用 Sleep 来模拟需要花费一些时间完成的工作。 它不调用窗体的 TextBox 控件。 TextBox 控件的 Text 属性在 RunWorkerCompleted 事件处理程序中直接设置。
// This event handler starts the form's我就是想问怎么写?
追答 //定义一个委托private object obj = new object();
private void 线程方法(object ps)
{
lock (obj)//加锁
{
WriteLog("aaaa");//给你的控件赋值
}
}