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
其大小会根据硬件配置不同而不同。
- c# 线程笔记2
- C#线程学习笔记2
- C#线程参考手册Chapter 2笔记
- C#学习笔记-线程
- 读C#线程及线程池笔记
- C#学习笔记 线程操作
- C#学习笔记 线程同步
- C#学习笔记之线程
- C#线程池学习笔记
- C#线程参考手册Chapter 1笔记
- [C#基础]线程学习笔记(一)
- [C#基础]线程学习笔记(二)
- C#学习笔记 线程同步问题
- 读C#线程方面知识做笔记
- C#笔记 跨线程操作控件
- C#线程更新UI控件笔记
- C#进程 线程学习笔记1
- Java线程笔记2
- 分享一个jQuery动态网格布局插件:Masonry
- AppFuse 2.1.0 调试成功 发帖留念……
- MultiMultiTouchTouch
- 浅解 go 语言的 interface
- 字符编解码的故事(ASCII,ANSI,Unicode,Utf-8区别)
- c# 线程笔记2
- linux下的GDB调试程序
- C++中如何强制inline函数(MSVC, GCC)
- Web页面父子窗口交互总结
- C++ primer第四版15.9节案例吐血实现
- 本周你不可错过的iOS游戏
- android连网详解——android.net、org.apache.http联网实现
- GEF 框架中的设计模式
- 构造函数重载