[WPF]c#启动多线程和更新UI的方法,及线程锁共享数据
版权声明:
本文为博主原创文章,转载请声明原文链接...谢谢。o_0。
更新时间:
2017-08-22 09:59:35
温馨提示:
学无止境,技术类文章有它的时效性,请留意文章更新时间,如发现内容有误请留言指出,防止别人"踩坑",我会及时更新文章
启动一个线程的方法
第一种快速启动
Thread t = new Thread(()=>{
//纯程中运行的代码
});
t.Start();第二种启动方法
Thread newWindowThread = new Thread(new ThreadStart(ThreadStartingPoint));
newWindowThread.SetApartmentState(ApartmentState.STA);//这里不用动
newWindowThread.IsBackground = true;
newWindowThread.Start();
//线程调用方法
private void ThreadStartingPoint()
{
//下面写一些在线程中处理的方法
////////////////////////////
System.Windows.Threading.Dispatcher.Run();
}启动一个带参数线程的方法
线程可以传入复杂一点的参数
var hello = "hello world";
var arr =new[] { 1,2,3};
//如果写成Thread thread = new Thread(ThreadMainWithParameters(hello));这种形式,编译时就会报错
Thread thread = new Thread(() => ThreadStartingPointWithPara(hello));
thread.Start();
//线程调用方法
private void ThreadStartingPointWithPara(string str)
{
//下面写一些在线程中处理的方法
Console.WriteLine("Running in a thread,received: {0}", str);
}线程更新ui
解决方案之一就是使用WPF的Dispatcher线程模型来修改,BeginInvoke(异步)会立即返回,Invoke(同步)会等执行完后再返回
//去操作ui线程元素
this.Dispatcher.Invoke(new Action(() =>
{
//这里进行一些ui上的操作
}));
//去操作ui线程元素
this.Dispatcher.BeginInvoke(new Action(() =>
{
//这里进行一些ui上的操作
}));线程锁同步共享数据
同一个变量多线程访问时可能一个线程还没有对这个变量处理完,就被其它线程修改啦,这个时候就需要同步啦
private static object o = new object();
lock (o)
{
//把同一时间只能有一个线程访问的数据放这里面
}