本节主要内容
** WinForm 跨线程更新UI **
-
通过UI线程的SynchronizationContext的Post/Send方法更新;
-
通过UI控件的Invoke/BegainInvoke方法更新;
-
通过BackgroundWorker取代Thread执行异步操作;
-
通过设置窗体属性,取消线程安全检查来避免"跨线程操作异常"(非线程安全,建议不使用)。
静态类不能实例化
吞吐能力
System.Threading
System.Threading.Tasks
TPL : Task Parallel Library
PLINQ : Parallel LINQ
LINQ :language integrated query 语言集成查询
耗时,网络请求,硬盘读写,
线程不在;现场还在,但是没干活;线程轮询
async
await
Event-based Asynchronous Pattern (EAP)
IAsyncResult,BeginMethod Name,
EndMethodName,
Task Parallel Library
Async return types,void,Task,Task,async is not part of the signature of the method,
overriding methods and implementing interfaces completely ignore the async keyword,
TAP Task-based Asynchronous Pattern,
cold Task
hot Task
In the case of a UI application, that means the code before the first await runs in the UI thread. Likewise, in an ASP.NET web application, it runs in an ASP.NET worker thread.
There is a thread waiting for network requests to complete, but it is shared between all network requests. It’s called the IO completion port thread on Windows.
SynchronizationContext
The current SynchronizationContext is a property of the current thread.
The important method of SynchronizationContext is Post
为什么异步编程重要?
异步编程为什么最难?
线程安全
什么时候需要处理共享资源
什么时候保证独占访问
线程独占资源
1兆的栈stack
线程本地存储TLS
寄存器状态
线程间共享资源
堆内存heap
操作系统句柄
operating system handles
比如打开文件,需要主动关闭
As soon as you type new Thread(), it’s over; your project already has legacy code.
catch ,finally 不要用 await,
lock 不要用 await
网友评论