.NET多線程編程是跨語言的,跨環(huán)境的,所以我們得學好它,對應用程序的性能提高是有幫助的。下面是西安達內.NET培訓(http://www.xatarena.cn/net/index.jhtml)講師總結的多線程調用函數(shù)的相關注意點,重點偏向應用和記憶。
1.多線程調用無參函數(shù)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace 多線程
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("主線程開始");
Thread t = new Thread(new ThreadStart(ShowTime));//注意ThreadStart委托的定義形式
t.Start();//線程開始,控制權返回Main線程
Console.WriteLine("主線程繼續(xù)執(zhí)行");
//while (t.IsAlive == true) ;
Thread.Sleep(1000);
t.Abort();
t.Join();//阻塞Main線程,直到t終止
Console.WriteLine("--------------");
Console.ReadKey();
}
static void ShowTime()
{
while (true)
{
Console.WriteLine(DateTime.Now.ToString());
}
}
}
}
可見其對傳遞進來的函數(shù)要求是:返回值void,無參數(shù)。
2.多線程調用帶參函數(shù)(兩種方法)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
3.線程同步
線程同步的方法有很多很多種volatile、Lock、InterLock、Monitor、Mutex、ReadWriteLock。這里用lock說明問題:在哪里同步,用什么同步,同步誰?
|
 |
|