使用backgroundworker元件,將**組織為一系列的事件及事件處理器。
這種方式稱為基於事件的非同步模式(event-based asynchronous pattern,簡稱eap)。這是歷史上第二種用來構造非同步程式的方式,現在更推薦使用tpl。using system;
using system.componentmodel;
using system.threading;
namespace 使用backgroundworker元件
; bw.dowork += worker_dowork;
bw.progresschanged += worker_progresschanged;
bw.runworkercompleted += worker_completed;
bw.runworkerasync();
console.writeline("press c to cancel work");
do} while (bw.isbusy);
}private
static
void
worker_dowork(object sender, doworkeventargs e)
; is thread pool thread: ",
thread.currentthread.managedthreadid,thread.currentthread.isthreadpoolthread);
var bw = (backgroundworker) sender;
for (var i = 0; i <=100; i++)
if (i%10==0)
thread.sleep(timespan.fromseconds(0.1));
}e.result = 42;
}private
static
void
worker_progresschanged(object sender, progresschangedeventargs e)
% completed. progress thread pool thread id: ",e.progresspercentage,
thread.currentthread.managedthreadid);
}//非同步操作完成或取消後觸發的事件程式
private
static
void
worker_completed(object sender, runworkercompletedeventargs e)
",thread.currentthread.managedthreadid);
if (e.error != null)
has occured.",e.error.message);
}else
if (e.cancelled)
else
",e.result);}}
}}
備註:學習《multithreading in c# 5.0 cookbook》eugene agafonov著的總結,以備日後查詢。
併發7 執行緒池
用優雅的方式理解和使用執行緒池 執行緒池的目的 1 減少系統維護執行緒的開銷 2 解耦,執行和建立分開 3 執行緒可以復用 執行緒池的使用 1 介面executor 提供方法execute runnable 執行執行緒命令 2 介面executorservice 提供方法shutdown 啟動一次順...
執行緒池使用
1.定義乙個執行緒池,用來執行實現callable介面的任務類.當阻塞佇列新添乙個任務類時,將while迴圈新增設定乙個變數startexcute,當阻塞佇列新添第乙個任務時,將startexcute設定為true,並呼叫excutetaskcall方法,使用執行緒池執行阻塞佇列的任務。當阻塞隊列為...
執行緒池使用
一 執行緒池的構造器 public threadpoolexecutor int corepoolsize,int maximumpoolsize,long keepalivetime,timeunit unit,blockingqueueworkqueue,threadfactory thread...