您的位置:知识库 » .NET技术

闲话“多线程”

作者: 圣殿骑士  来源: 博客园  发布时间: 2010-08-04 14:30  阅读: 1379 次  推荐: 0   原文链接   [收藏]  

一,摘要

        圣殿骑士首先向大家说声对不起,由于最近身体不适,同时也因为这些天一直在研究微软的云计算平台Windows Azure(公司项目需要),所以暂停了更新WPF 基础到企业应用系列索引,不过经过这几天的调节,尤其是到海边去晒了晒太阳,现在又开始继续发文了,大家有兴趣也可以去看看漂亮的大海图片工作之余的闲暇,今天这篇文章不是专业谈多线程,只是应一些朋友的要求对上篇文章WPF 基础到企业应用系列4——WPF千年轮回进行一些额外的补充,如果有时间,可以单独写一个专题来详细深入多线程的应用,当然由于自己才疏学浅,但渴求对自己知识的纠正和提高,所以发布出来。如有不对的地方,也希望大家多多海涵!

二,提纲

一,摘要

二,提纲

三,基本概念

四,多线程实践

五,总结

三,基本概念

什么是进程?

“进程”是操作系统的最基本的,也是最重要的概念之一。简单来说一个进程就是你正在执行的应用程序,一个进程里面包括一个或多个线程。系统中的一个进程肯定对应着一个应用程序,但同一个应用程序可以有多个进程。所以我们要清楚,进程和程序是相关联的,但并不是同一个概念。即应用程序被加载到内存中后叫进程。

什么是线程?

线程简单来说就是程序中的一个执行流,每个线程都有自己的专有寄存器同时代码区是共享的,即不同的线程可以执行同样的函数和访问同样的变量。 即进程被CPU处理时叫线程。

什么是多线程? 

 多线程简单的说就是在一个程序中包含多个程序流,可以把一个复杂的操作分成多个细节操作,这些细节操作可以并行的执行,从而节约时间和提高效率。

多线程优点:

 线程可以有以下一些好处:可以提高CPU的利用率。在一个多线程程序中,一个线程处于等待的时候,CPU可以运行其它的线程来处理,这样就节约了时间和提高了程序的效率,同时也提高了用户的体验。

多线程缺点: 

1,线程越多,内存占用越大;

2,多线程的运行需要互相协调和统一管理,CPU会额外跟踪线程;
3,线程之间对共享资源的访问会相互影响,必须解决竞用共享资源的种种问题;
4,线程太多会导致控制的复杂度增加,会引发不必要的Bug;

5,在32位的操作系统和64位的操作系统执行的线程、版本不同的操作系统之间执行的线程等都有所差异,执行顺序也有差异。

重要概念(本篇不重点讲解)

Start():启动线程;
Sleep(int):暂停当前线程指定的毫秒数;
Abort():通常使用该方法来终止一个线程,但容易出错;
Suspend():挂起线程,需要时可以恢复;
Resume():恢复被Suspend()方法挂起的线程;

程的优先级可以定义为ThreadPriority枚举的值,即Highest、AboveNormal、Normal、BelowNormal和 Lowest;

创建线程可以用如下三种方式:Thread、ThreadPool、Timer;

.NET Framework内置提供了三种Timer:System.Windows.Forms.Timer、System.Timers.Timer和System.Threading.Timer;

线程同步lock,Monitor,同步事件EventWaitHandler,互斥体Mutex、线程池等的使用;

四,多线程实践

        在本文中我们会通过11个小Demo来讲解一下多线程的实践,讲得不是很全面,只是希望给大家一个参考。由于比较简单,所以我就不添加累赘的文字介绍,这样大家看起来也比较舒畅。我会在文章后面附上代码,大家可以下载进行查看和调试。

这个11个方法都通过Form1_Load调用,如下面的代码和图片:

private void Form1_Load(object sender, EventArgs e)
{
DoWithEasy();
DoWithParameter();
DoWithTimer();
DoWithThreadPool();
DoWithThreadPoolParameter();
DoWithAnonymous();
DoWithLambda();
DoWithCommon();
DoWithAction();
DoWithFunc();
DoWithPredicate();
}

thread

创建一个简单的线程:

private void DoWithEasy()
{
Thread t = new Thread(new ThreadStart(this.DoSomethingWithEasy));
t.Start();
}
private void DoSomethingWithEasy()
{
MessageBox.Show("Knights Warrior");
}

创建一个带参数的线程:

private void DoWithParameter()
{
Thread t = new Thread(new ParameterizedThreadStart(this.DoSomethingWithParameter));
t.Start("Knights Warrior");
}
private void DoSomethingWithParameter(object x)
{
MessageBox.Show(x.ToString());
}

 

使用Timer创建线程:

public void DoWithTimer()
{

System.Windows.Forms.Timer timer = new System.Windows.Forms.Timer();
timer.Interval = 1000;
timer.Tick += (x, y) =>
{
MessageBox.Show("Knights Warrior");
};
timer.Start();
}

通过ThreadPool创建无参线程:

private void DoWithThreadPool()
{
ThreadPool.QueueUserWorkItem(new WaitCallback(this.DoSomethingWithThreadPoolNO));
}
private void DoSomethingWithThreadPoolNO(object x)
{
MessageBox.Show("Knights Warrior");
}

通过ThreadPool创建有参线程:

private void DoWithThreadPoolParameter()
{
ThreadPool.QueueUserWorkItem(new WaitCallback(this.DoSomethingWithThreadPoolParameter), "Knights Warrior");
}
private void DoSomethingWithThreadPoolParameter(object x)
{
MessageBox.Show(x.ToString());
}

通过匿名委托方式创建线程:

private void DoWithAnonymous()
{
ThreadPool.QueueUserWorkItem(new WaitCallback(delegate(object x)
{
MessageBox.Show("Knights Warrior");
}));
}

通过lambda的方式创建线程:

private void DoWithLambda()
{
ThreadPool.QueueUserWorkItem(new WaitCallback(x =>
{
MessageBox.Show("Knights Warrior");
}));
}

线程更新UI(自定义委托的方式):

private void DoWithCommon()
{
WaitCallback waitCallBack = new WaitCallback(this.InvokeMethod);
ThreadPool.QueueUserWorkItem(waitCallBack, "Knights Warrior");
}

private delegate void InvokeMethodDelegate(string name);
private void InvokeMethod(object x)
{
this.Invoke(new InvokeMethodDelegate(this.ChangeUIWithCommon), x.ToString());
}

private void ChangeUIWithCommon(string name)
{
this.lblMessage.Text = name;
}

线程更新UI(通过Action委托)

private void DoWithAction()
{
WaitCallback waitCallback = new WaitCallback(this.DoSomethingWithAction);
ThreadPool.QueueUserWorkItem(waitCallback, "Knights Warrior");
}

private void DoSomethingWithAction(object x)
{
this.Invoke(new Action<string>(this.ChangeUI), x.ToString());
}

private void ChangeUI(string message)
{
this.lblMessage.Text = message;
}

线程更新UI(通过Func委托)

private void DoWithFunc()
{
WaitCallback waitCallback = new WaitCallback(this.DoSomethingWithFunc);
ThreadPool.QueueUserWorkItem(waitCallback, "Knights Warrior");
}

private void DoSomethingWithFunc(object x)
{
Func<string, int> f = new Func<string, int>(this.GetFuncMessage);
object result = this.Invoke(f, x.ToString());
MessageBox.Show(result.ToString());
}

private int GetFuncMessage(string message)
{
this.lblMessage.Text = message;
if (message == "Knights Warrior")
{
return 1;
}
else
{
return 0;
}
}

线程更新UI(通过Predicate委托)

private void DoWithPredicate()
{
WaitCallback waitCallback = new WaitCallback(this.DoSomethingWithPredicate);
ThreadPool.QueueUserWorkItem(waitCallback, "Knights Warrior");
}

private void DoSomethingWithPredicate(object x)
{
Predicate<string> pd = new Predicate<string>(this.GetPredicateMessage);
object result = this.Invoke(pd, x);
MessageBox.Show(result.ToString());
}

private bool GetPredicateMessage(string message)
{
this.lblMessage.Text = message;
if (message == "Knights Warrior")
{
return true;
}
else
{
return false;
}
}

概念注解:

Predicate 委托

定义:public delegate bool Predicate<T>(T obj);

表示定义一组条件并确定指定对象是否符合这些条件的方法。这个委托经常由 Array 和 List 类的几种方法使用,用于在集合中检索元素。

Func 委托

  定义:public delegate TResult Func<T, TResult>(T arg);
 
代码
delegate TResult Func<T>();
delegate TResult Func<T1,TResult>(T1 arg1);
delegate TResult Func<T1,T2,TResult>(T1 arg1, T2 arg2);
delegate TResult Func<T1,T2,T3,TResult>(T1 arg1, T2 arg2, T3 arg3);
delegate TResult Func<T1,T2,T3,T4,TResult>T1 arg1, T2 arg2, T3 arg3, T4 arg4);

Func():封装一个不具有参数并返回 TResult 的类型值的方法。
Func<T, TResult> 封装一个具有一个参数并返回 TResult 的类型值的方法。

Action 委托

  定义:public delegate void Action<T>(T obj);
代码
delegate void Action<T>(T1 arg1);
delegate void Action<T1,T2>(T1 arg1, T2 arg2);
delegate void Action<T1,T2,T3>T1 arg1, T2 arg2, T3 arg3);
delegate void Action<T1,T2,T3,T4>T1 arg1, T2 arg2, T3 arg3, T4 arg4)

Action<T1, T2>:封装一个带有两个参数并且无返回值的方法。

这三个委托经常会用到,区分也很简单:
Predicate
接受一个T的参数,返回一个bool值,可以用
Func实现此功能 
Func
接受1到4个参数,返回一个值; 

Action
接受1到4个参数,无返回值;

五,总结

         这篇文章并没有什么深度和难度,只是对多线程进行了一下小结,如果大家想了解更多,我会单独详细写一些多线程相关的文章,当然由于本人知识有限,文中错误之处也敬请海涵!下一篇开始我们将继续更新WPF 基础到企业应用系列索引系列文章,如果有感兴趣的同仁,敬请关注!

0
0
标签:多线程 。Net

.NET技术热门文章

    .NET技术最新文章

      最新新闻

        热门新闻