闽公网安备 35020302035485号
class ThreadTest2
{
bool done;
static void Main()
{
ThreadTest2 tt = new ThreadTest2(); // Create a common instance
new Thread(tt.Go).Start();
tt.Go();
}
// Note that Go is now an instance method
void Go()
{
if (!done)
{
done = true;
Console.WriteLine("Done");
}
}
}
运行结果如下:Done1.2、线程抢占
class ThreadTest2
{
bool done;
static void Main()
{
ThreadTest2 tt = new ThreadTest2(); // Create a common instance
new Thread(tt.Go).Start();
tt.Go();
}
// Note that Go is now an instance method
void Go()
{
if (!done)
{
Console.WriteLine("Done");
done = true;
}
}
}
运行结果如下:Done Done线程抢占例子2:
for (int i = 0; i < 10; i++) new Thread (() => Console.Write (i)).Start();运行结果
02235577991.3、避免线程抢占
class ThreadTest2
{
static readonly object locker = new object();
bool done;
static void Main()
{
ThreadTest2 tt = new ThreadTest2(); // Create a common instance
new Thread(tt.Go).Start();
tt.Go();
}
// Note that Go is now an instance method
void Go()
{
lock (locker)
{
if (!done)
{
Console.WriteLine("Done");
done = true;
}
}
}
}
运行结果如下:Done二、线程阻塞
class Program
{
static void Main()
{
Thread t = new Thread(Go);
t.Start();
t.Join();
Console.WriteLine("Thread t has ended!");
}
static void Go()
{
for (int i = 0; i < 1000; i++) Console.Write("y");
}
}
运行结果:
Thread.Sleep (500);也会阻塞线程,让渡CPU的执行权给其他线程。
在多处理器计算机上,多线程是通过时间片和真正的并发实现的,其中不同的线程在不同的CPU上同时运行代码。几乎可以肯定,由于操作系统需要服务自己的线程以及其他应用程序的线程,因此还会有一定的时间片。当线程的执行由于诸如时间片之类的外部因素而被中断时,该线程被认为是被抢占的。在大多数情况下,线程无法控制其被抢占的时间和地点。
static void Main()
{
Thread t = new Thread(() =>Print("Hello from t!"));
t.Start();
}
static void Print(string message)
{
Console.WriteLine(message);
}
7.2、线程start方法传参static void Main()
{
Thread t = new Thread(Print);
t.Start("Hello from t!");
}
static void Print(object messageObj)
{
string message = (string)messageObj;
// We need to cast here
Console.WriteLine(message);
}
7.3、线程创建需要时间string text = "t1"; Thread t1 = new Thread ( () => Console.WriteLine (text) ); text = "t2"; Thread t2 = new Thread ( () => Console.WriteLine (text) ); t1.Start(); t2.Start();运行结果:
t2 t2以上运行结果说明,在t1线程创建之前text被修改成了t2。
static void Main()
{
Thread.CurrentThread.Name = "main";
Thread worker = new Thread(Go);
worker.Name = "worker";
worker.Start();
Go();
}
static void Go()
{
Console.WriteLine("Hello from " + Thread.CurrentThread.Name);
}
运行结果:Hello from main Hello from worker九、前台线程与后台线程
Thread worker = new Thread(() => Console.ReadLine());
if (args.Length > 0) worker.IsBackground = true;
worker.Name = "backThread";
worker.Start();
Console.WriteLine("finish!");
前台线程会随着主线程窗口关闭而停止,后台线程及时主线程窗口关闭自己独立运行。enum ThreadPriority { Lowest, BelowNormal, Normal, AboveNormal, Highest }
有时候提高了线程的优先级,但却仍然无法满足一些实时的应用需求,这时候就需要提高进程的优先级,System.Diagnostics命名空间中的process进程类.using (Process p = Process.GetCurrentProcess()) p.PriorityClass = ProcessPriorityClass.High;实际上,ProcessPriorityClass.High比最高优先级低1个级别:Realtime。将进程优先级设置为Realtime,可指示OS,您永远不希望该进程将CPU时间浪费在另一个进程上。如果您的程序进入意外的无限循环,您甚至可能会发现操作系统已锁定,只剩下电源按钮可以拯救您!因此,高通常是实时应用程序的最佳选择。
public static void Main()
{
try
{
new Thread(Go).Start();
Console.ReadKey();
}
catch (Exception ex)
{
// We'll never get here!
Console.WriteLine("Exception!");
}
}
static void Go() { throw null; } // Throws a NullReferenceException
static void GoCatch()
{
try
{
// ...
throw null; // The NullReferenceException will get caught below
// ...
}
catch (Exception ex)
{
// Typically log the exception, and/or signal another thread
// that we've come unstuck
// ...
Console.WriteLine("exception.");
}
}
十二、线程池static void Main() // The Task class is in System.Threading.Tasks
{
var task=Task.Factory.StartNew(Go);
Console.WriteLine("main");
task.Wait() ;
Console.WriteLine(task.Result);
Console.ReadLine();
}
static string Go()
{
if (Thread.CurrentThread.IsThreadPoolThread)
{ Console.WriteLine("Hello from the thread pool!"); }
else { Console.WriteLine("Hello just from the thread!"); }
return "task complete!";
}
输出结果:main Hello from the thread pool! task complete!12.1.1、Task异常捕获
static void Main() // The Task class is in System.Threading.Tasks
{
var task=Task.Factory.StartNew(Go);
Console.WriteLine("main");
try
{ task.Wait(); }
catch (Exception e)
{
Console.WriteLine("exception!");
}
Console.WriteLine(task.Result);
Console.ReadLine();
}
static string Go()
{
if (Thread.CurrentThread.IsThreadPoolThread)
{ Console.WriteLine("Hello from the thread pool!"); }
else { Console.WriteLine("Hello just from the thread!"); }
throw null;
return "task complete!";
}
运行结果,在主线程中捕获到了其他线程的异常:
static void Main()
{
// Start the task executing:
Task<string> task = Task.Factory.StartNew<string>
( () => DownloadString ("http://www.linqpad.net") );
// We can do other work here and it will execute in parallel:
RunSomeOtherMethod();
// When we need the task's return value, we query its Result property:
// If it's still executing, the current thread will now block (wait)
// until the task finishes:
string result = task.Result;
}
static string DownloadString (string uri)
{
using (var wc = new System.Net.WebClient())
return wc.DownloadString (uri);
}
Task<string> 就是一个返回值为string的异步委托。static void Main()
{
ThreadPool.QueueUserWorkItem(Go);
ThreadPool.QueueUserWorkItem(Go, 123);
Console.ReadLine();
}
static void Go(object data) // data will be null with the first call.
{
Console.WriteLine("Hello from the thread pool! " + data);
}
运行结果:Hello from the thread pool! Hello from the thread pool! 123与Task不同:
ThreadPool.SetMinThreads (50, 50);