Delphi中多线程用Synchronize实现VCL数据同步显示
生活随笔
收集整理的這篇文章主要介紹了
Delphi中多线程用Synchronize实现VCL数据同步显示
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
概述:
VCL實現同步的另一種方法就是調用線程類的Synchronize的過程,此過程需要一個無參數的procedure,故在此procedure中無法傳遞參數值,但可以通過類的成員來實現。在類的Execute中只須調用Synchronize就可以了。
實現:
關鍵在于對Synchronize參數的定義。定義一個無參數的procedure通過它來訪問類的成員變量szName和nIndex。在類的重載Execute中調用Synchronize。
子類的定義如下:
unit?TChildThread; ? interface ? uses ?Classes,Messages,Windows,SysUtils; ? const?MAX_LEN?=?260; type ?TChildThreads?=?class(TThread) ?private ????{?Private?declarations?} ?protected procedure?Execute;?override; //同步函數的聲明 ????procedure?UpdateData; ?public ?????szName?:?array[0..MAX_LEN]?of?Char; ????nIndex?:?Integer; ?end; ? implementation uses ???????Unit1; ? {?Important:?Methods?and?properties?of?objects?in?VCL?or?CLX?can?only?be?used ?in?a?method?called?using?Synchronize,?for?example, ? ??????Synchronize(UpdateCaption); ? ?and?UpdateCaption?could?look?like, ? ????procedure?TChildThread.UpdateCaption; ????begin ??????Form1.Caption?:=?'Updated?in?a?thread'; ????end;?} ? {?TChildThread?} //同步函數的實現 procedure?TChildThreads.UpdateData; begin ???????Form1.ShowData.Items.Add(PChar(@szName)); end; ? procedure?TChildThreads.Execute; begin ?{?Place?thread?code?here?} ?//調用同步過程 ?Synchronize(UpdateData); end; ? end.
主程的設計與《Delphi中多線程用消息實現VCL數據同步顯示》基本一致,但為了與其顯示相同結果,在生成子線程中語句順序作了一下調整。以下代碼僅顯示與上一篇不同的一個過程,其它代碼不再贅述。 procedure?TForm1.StartThreadsClick(Sender:?TObject); var ???????oChildThread?:?array[0..1000]?of?TChildThreads; ?i?:?Integer; begin ???????For?i?:=?0?to?1000?do ?begin ?????oChildThread[i]?:=?TChildThreads.Create(true); ????//注意這里的代碼與消息同步中的順序。 ????oChildThread[i].nIndex?:=?i; ????strcopy(@oChildThread[i].szName,PChar('Child'?+?IntToStr(i))); ????oChildThread[i].Resume; ?end; ? end; 轉載地址:http://blog.csdn.net/maxcode/article/details/726766
主程的設計與《Delphi中多線程用消息實現VCL數據同步顯示》基本一致,但為了與其顯示相同結果,在生成子線程中語句順序作了一下調整。以下代碼僅顯示與上一篇不同的一個過程,其它代碼不再贅述。
總結
以上是生活随笔為你收集整理的Delphi中多线程用Synchronize实现VCL数据同步显示的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: delphi char与string比较
- 下一篇: 代码走查样板单