Delphi Thread Pool Example Using AsyncCalls 异步调用.docx
- 文档编号:2362527
- 上传时间:2022-10-29
- 格式:DOCX
- 页数:6
- 大小:18.16KB
Delphi Thread Pool Example Using AsyncCalls 异步调用.docx
《Delphi Thread Pool Example Using AsyncCalls 异步调用.docx》由会员分享,可在线阅读,更多相关《Delphi Thread Pool Example Using AsyncCalls 异步调用.docx(6页珍藏版)》请在冰豆网上搜索。
DelphiThreadPoolExampleUsingAsyncCalls异步调用
DelphiThreadPoolExampleUsingAsyncCalls异步调用
DelphiThreadPoolExampleUsingAsyncCallsAsyncCallsUnitByAndreasHausladen-Let'sUse(andExtend)It!
ByZarkoGajic,AGuide
SeeMoreAbout:
delphimultithreadingtthreadclassasynccalls
DelphiThreadPoolExampleUsingAsyncCallsThisismynexttestprojecttoseewhatthreadinglibraryforDelphiwouldsuitemebestformy"filescanning"taskIwouldliketoprocessinmultiplethreads/inathreadpool.
Torepeatmygoal:
transformmysequential"filescanning"of500-2000+filesfromthenonthreadedapproachtoathreadedone.Ishouldnothave500threadsrunningatonetime,thuswouldliketouseathreadpool.Athreadpoolisaqueue-likeclassfeedinganumberofrunningthreadswiththenexttaskfromthequeue.
Thefirst(verybasic)attemptwasmadebysimplyextendingtheTThreadclassandimplementingtheExecutemethod(mythreadedstringparser).
SinceDelphidoesnothaveathreadpoolclassimplementedoutofthebox,inmysecondattemptI'vetriedusingOmniThreadLibrarybyPrimozGabrijelcic.
OTLisfantastic,haszillionwaystorunataskinabackground,awaytogoifyouwanttohave"fire-and-forget"approachtohandingthreadedexecutionofpiecesofyourcode.
AsyncCallsbyAndreasHausladen
Note:
whatfollowswouldbemoreeasytofollowifyoufirstdownloadthesourcecode.
WhileexploringmorewaystohavesomeofmyfunctionsexecutedinathreadedmannerI'vedecidedtoalsotrythe"AsyncCalls.pas"unitdevelopedbyAndreasHausladen.Andy'sAsyncCalls–AsynchronousfunctioncallsunitisanotherlibraryaDelphidevelopercanusetoeasethepainofimplementingthreadedapproachtoexecutingsomecode.
FromAndy'sblog:
WithAsyncCallsyoucanexecutemultiplefunctionsatthesametimeandsynchronizethemateverypointinthefunctionormethodthatstartedthem....TheAsyncCallsunitoffersavarietyoffunctionprototypestocallasynchronousfunctions....Itimplementsathreadpool!
Theinstallationissupereasy:
justuseasynccallsfromanyofyourunitsandyouhaveinstantaccesstothingslike"executeinaseparatethread,synchronizemainUI,waituntilfinished".
Besidethefreetouse(MPLlicense)AsyncCalls,AndyalsofrequentlypublisheshisownfixesfortheDelphiIDElike"DelphiSpeedUp"and"DDevExtensions"I'msureyou'veheardof(ifnotusingalready).
AsyncCallsInAction
Whilethere'sonlyoneunittoincludeinyourapplication,theasynccalls.pasprovidesmorewaysonecanexecuteafunctioninadifferentthreadanddothreadsynchronization.TakealookatthesourcecodeandtheincludedHTMLhelpfiletogetfamiliarwiththebasicsofasynccalls.
Inessence,allAsyncCallfunctionsreturnanIAsyncCallinterfacethatallowstosynchronizethefunctions.IAsnycCallexposesthefollowingmethods:
//v2.98ofasynccalls.pas
IAsyncCall=interface
//waitsuntilthefunctionisfinishedandreturnsthereturnvalue
functionSync:
Integer;
//returnsTruewhentheasynchronfunctionisfinished
functionFinished:
Boolean;
//returnstheasynchronfunction'sreturnvalue,whenFinishedisTRUE
functionReturnValue:
Integer;
//tellsAsyncCallsthattheassignedfunctionmustnotbeexecutedinthecurrentthrea
procedureForceDifferentThread;
end;
AsIfancygenericsandanonymousmethodsI'mhappythatthere'saTAsyncCallsclassnicelywrappingcallstomyfunctionsIwanttobeexecutedinathreadedmanner.
Here'sanexamplecalltoamethodexpectingtwointegerparameters(returninganIAsyncCall):
TAsyncCalls.Invoke(AsyncMethod,i,Random(500));
TheAsyncMethodisamethodofaclassinstance(forexample:
apublicmethodofaform),andisimplementedas:
functionTAsyncCallsForm.AsyncMethod(taskNr,sleepTime:
integer):
integer;
begin
result:
=sleepTime;Sleep(sleepTime);TAsyncCalls.VCLInvoke(
procedure
begin
Log(Format('done>nr:
%d/tasks:
%d/slept:
%d',[tasknr,asyncHelper.TaskCount,sleepTime]));
end);
end;
Again,I'musingtheSleepproceduretomimicsomeworkloadtobedoneinmyfunctionexecutedinaseparatethread.
TheTAsyncCalls.VCLInvokeisawaytodosynchronizationwithyourmainthread(application'smainthread-yourapplicationuserinterface).VCLInvokereturnsimmediately.Theanonymousmethodwillbeexecutedinthemainthread.There'salsoVCLSyncwhichreturnswhentheanonymousmethodwascalledinthemainthread.
ThreadPoolinAsyncCalls
Asexplainedintheexamples/helpdocument(AsyncCallsInternals-Threadpoolandwaiting-queue):
Anexecutionrequestisaddedtothewaiting-queuewhenanasync.functionisstarted...Ifthemaximumthreadnumberisalreadyreachedtherequestremainsinthewaiting-queue.Otherwiseanewthreadisaddedtothethreadpool.
Backtomy"filescanning"task:
whenfeeding(inaforloop)
- 配套讲稿:
如PPT文件的首页显示word图标,表示该PPT已包含配套word讲稿。双击word图标可打开word文档。
- 特殊限制:
部分文档作品中含有的国旗、国徽等图片,仅作为作品整体效果示例展示,禁止商用。设计者仅对作品中独创性部分享有著作权。
- 关 键 词:
- Delphi Thread Pool Example Using AsyncCalls 异步调用 异步 调用
![提示](https://static.bdocx.com/images/bang_tan.gif)
链接地址:https://www.bdocx.com/doc/2362527.html