C#中使用多线程

一、同步上下文
同步上下文可用于在线程上下文中更新UI控件
1. 定义一个上下文
SynchronizationContext synchronizationContext = null;
2. 在表单Form的初始化函数中初始化该上下文
SynchronizationContext synchronizationContext = SynchronizationContext.Current;
3. 更新UI控件内容
定义一个回调函数
public void updateMessage(object obj)
{
    textBox4.AppendText(obj.ToString());
    textBox4.AppendText(Environment.NewLine);
}
Post一条消息
synchronizationContext_m.Post(updateMessage, "The connection has been established ...");

二、启动线程
Thread thread = new Thread(new ParameterizedThreadStart(socketThread)); // 传入一个参数
thread.IsBackground = true;
thread.Start(socketAddress);
线程函数
public void socketThread(object obj)
{
    ...
}
如果线程函数不需要传入参数,可以直接用
New ThreadStart()

猜你喜欢

转载自www.cnblogs.com/ycz0926/p/10520854.html