c# 线程笔记2

来源:互联网 发布:什么是电子数据交换 编辑:程序博客网 时间:2024/06/09 20:41
 

10.通过TPL进入线程池。
 10.1 Task 类在in System.Threading.Tasks名字空间中,并且4.0以后才支持。
static void Main() //
{
Task.Factory.StartNew (Go);
}
static void Go()
{
Console.WriteLine ("Hello from the thread pool!");
}
 10.2 可以对返回值进行等待。
 static void Main()
{
// 执行任务
Task<string> task = Task.Factory.StartNew<string>( () => DownloadString ("http://www.linqpad.net") );
// 并行做其他工作
RunSomeOtherMethod();
//等待执行结果,当前线程会阻塞。
string result = task.Result;
}
static string DownloadString (string uri)
{
using (var wc = new System.Net.WebClient())
return wc.DownloadString (uri);
}

 11 4.0以前的版本进入线程池

 11.1 QueueUserWorkItem:不提供返回值
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);
}
// Output:
Hello from the thread pool!
Hello from the thread pool! 123
该方式不提供返回值,并且需要自己在代码内处理异常,任何未处理异常将造成系统崩溃。
11.2 Asynchronous delegates
可以任意传入传出参数,并且不需要对异常特别处理。
实例:
static void Main()
{
Func<string, int> method = Work;
IAsyncResult cookie = method.BeginInvoke ("test", null, null);
//
// ...此处并行处理其他工作...
//
int result = method.EndInvoke (cookie);
Console.WriteLine ("String length is: " + result);
}
static int Work (string s) { return s.Length; }
EndInvoke做三件事:
a.如果任务未完成,则等待一部代理完成执行工作。
b.获取返回值,可以是任意ref或out参数
c.抛出未处理异常到调用线程。
11.3在调用BeginInvoke时你可以指定一个回调代理,这是一个接收IAsyncResult对象的方法。如下所示:
static void Main()
{
Func<string, int> method = Work;
method.BeginInvoke ("test", Done, method);
// ...
//
}
static int Work (string s) { return s.Length; }
static void Done (IAsyncResult cookie)
{
var target = (Func<string, int>) cookie.AsyncState;
int result = target.EndInvoke (cookie);
Console.WriteLine ("String length is: " + result);
}
12.优化线程池
  线程池上限配置如下:
· 1023 in Framework 4.0 in a 32-bit environment
· 32768 in Framework 4.0 in a 64-bit environment
· 250 per core in Framework 3.5
· 25 per core in Framework 2.0
其大小会根据硬件配置不同而不同。

原创粉丝点击