WPF多线程使用示例

概况

  • 启动不带参数线程的方法
  • 启动带参数线程的方法
  • 线程更新UI
  • 线程锁同步共享数据

启动不带参数线程的方法

第一种快速启动

1
2
3
4
Thread t = new Thread(()=>{
    //下面写一些在线程中处理的方法
});
t.Start();

  

第二种启动方法

1
2
3
4
5
6
7
Thread newWindowThread = new Thread(new ThreadStart(ThreadStartingPoint));
newWindowThread.Start();
//线程调用方法
private void ThreadStartingPoint()
{
  //下面写一些在线程中处理的方法
}

  

启动带参数线程的方法

1
2
3
4
5
6
7
Thread thread = new Thread(() => ThreadStartingPointWithPara("hello"));
thread.Start();
//线程调用方法
private void ThreadStartingPointWithPara(string str)
{
    //下面写一些在线程中处理的方法
}

 

线程更新UI

解决方案之一就是使用WPF的Dispatcher线程模型来修改,BeginInvoke(异步)会立即返回,Invoke(同步)会等执行完后再返回

1
2
3
4
5
6
7
8
9
10
//同步操作UI线程元素
this.Dispatcher.Invoke(new Action(() =>
{
    //这里进行一些UI上的操作
}));
//异步操作UI线程元素
this.Dispatcher.BeginInvoke(new Action(() =>
{
    //这里进行一些UI上的操作
}));

    

线程锁同步共享数据

同一个变量多线程访问时可能一个线程还没有对这个变量处理完,就被其它线程修改,这个时候就需要同步。

1
2
3
4
5
private static object o = new object();
lock (o)
{
    //把同一时间只能有一个线程访问的数据放这里面
}

  

示例源码下载:ThreadWindow.zip

转自:https://www.cnblogs.com/microsoft-zh/p/14590736.html

原文地址:https://www.cnblogs.com/DoNetCShap/p/14772237.html