forked from douglasimcabral/pyscripter
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathAsyncCalls.pas
3525 lines (3048 loc) · 111 KB
/
AsyncCalls.pas
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
{**************************************************************************************************}
{ }
{ Asynchronous function calls utilizing multiple threads. }
{ }
{ The contents of this file are subject to the Mozilla Public License Version 1.1 (the "License"); }
{ you may not use this file except in compliance with the License. You may obtain a copy of the }
{ License at http://www.mozilla.org/MPL/ }
{ }
{ Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF }
{ ANY KIND, either express or implied. See the License for the specific language governing rights }
{ and limitations under the License. }
{ }
{ The Original Code is AsyncCalls.pas. }
{ }
{ The Initial Developer of the Original Code is Andreas Hausladen. }
{ Portions created by Andreas Hausladen are Copyright (C) 2006-2011 Andreas Hausladen. }
{ All Rights Reserved. }
{ }
{ Contributor(s): }
{ }
{**************************************************************************************************}
{ }
{ Version: 2.99 (2011-12-14) }
{ Added: IAsyncCall.CancelInvocation method }
{ Added: IAsyncCall.Forget method }
{ }
{ Version: 2.98 (2011-10-22) }
{ Added: Support for Delphi XE2 64bit }
{ }
{ Version: 2.97 (2011-05-21) }
{ Fixed: The thread priority wasn't reset to Normal for new AsyncCall tasks. }
{ Fixed: Replaced Suspend/Resume code to prevent a race condition where all threads are }
{ suspended but their FSuspended flag is false. }
{ Fixed: Exception handling in TAsyncCall.InternExecuteSyncCall. Quit() wasn't called after an }
{ exception was raised. }
{ }
{ Version: 2.96 (2010-09-12) }
{ Fixed: CoInitialize call was missing }
{ }
{ Version: 2.95 (2010-09-12) }
{ Added: Support for RAD Studio XE }
{ Added: Support for UnicodeString }
{ }
{ Version: 2.92 (2009-08-30) }
{ Added: Support for RAD Studio 2010 }
{ Restored: Delphi 2009 Update 1 fixed the compiler bug. All generic methods are now available. }
{ }
{ Version: 2.91 (2008-09-29) }
{ Fixed: All generic methods are now disabled due to an internal compiler error in Delphi 2009 }
{ }
{ Version: 2.9 (2008-09-27) }
{ Fixed: Window message handling }
{ Added: Delphi 2009 support with generics and anonymous methods }
{ Added: AsyncCall(Runnable: IAsyncRunnable) }
{ }
{ Version: 2.21 (2008-05-14) }
{ Fixed: Fixed bug in AsyncMultiSync }
{ }
{ Version: 2.2 (2008-05-12) }
{ Fixed: Bugs in main thread AsyncMultiSync implementation }
{ Added: Delphi 5 support }
{ }
{ Version: 2.1 (2008-05-06) }
{ Added: Delphi 6 support }
{ Added: Support for "Exit;" in the MainThread block }
{ Fixed: Exception handling for Delphi 6, 7 and 2005 }
{ Fixed: EBX, ESI and EDI weren't copied into the synchronized block (e.g. used for Self-Pointer)}
{ }
{ Version: 2.0 (2008-05-04) }
{ Added: EnterMainThread/LeaveMainThread }
{ Added: LocalVclCall, LocalAsyncVclCall, MsgAsyncMultiSync }
{ Added: LocalAsyncExec, AsyncExec }
{ Added: IAsyncCall.ForceDifferentThread }
{ Fixed: Exception handling }
{ Removed: Delphi 5 and 6 support }
{ }
{ Version: 1.2 (2008-02-10) }
{ Added: CoInitialize }
{ Added: LocalAsynCall() function }
{ }
{ Version: 1.1 (2007-08-14) }
{ Fixed: Workaround for TThread.Resume bug }
{ }
{ Version: 1.0 (2006-12-23) }
{ Initial release }
{**************************************************************************************************}
{$A+,B-,C-,D-,E-,F-,G+,H+,I+,J-,K-,L+,M-,N+,O+,P+,Q-,R-,S-,T-,U-,V+,W+,X+,Y+,Z1}
unit AsyncCalls;
{.$DEFINE DEBUG_ASYNCCALLS}
{.$DEFINE DEBUG_ASYNCCALLS_ODS}
{.$DEFINE DEBUG_THREADSTATS}
{$IFDEF MSWINDOWS}
{$IFNDEF CPUX64}
{$DEFINE SUPPORT_LOCAL_FUNCTIONS}
{$ENDIF ~CPUX64}
{$ENDIF MSWINDOWS}
interface
{$IFNDEF CONDITIONALEXPRESSIONS}
{$IFDEF VER130}
{$DEFINE DELPHI5}
{$ELSE}
'Your compiler version is not supported'
{$ENDIF}
{$ELSE}
{$IFDEF VER140}
{$DEFINE DELPHI6}
{.$MESSAGE ERROR 'Your compiler version is not supported'}
{$ELSE}
{$DEFINE DELPHI7_UP}
{$ENDIF}
{$WARN SYMBOL_PLATFORM OFF}
{$WARN UNIT_PLATFORM OFF}
{$IF CompilerVersion >= 15.0}
{$WARN UNSAFE_TYPE OFF}
{$WARN UNSAFE_CODE OFF}
{$WARN UNSAFE_CAST OFF}
{$IFEND}
{$IF CompilerVersion >= 18.0}
{$DEFINE SUPPORTS_INLINE}
{$IFEND}
{$IF CompilerVersion >= 20.0}
{$DEFINE DELPHI2009_UP}
{$IFEND}
{$IF CompilerVersion >= 21.0}
{$DEFINE DELPHI2010_UP}
{$IFEND}
{$ENDIF}
{$IFDEF DEBUG_ASYNCCALLS}
{$D+,C+}
{$ENDIF DEBUG_ASYNCCALLS}
uses
Windows, Messages, SysUtils, Classes, Contnrs, ActiveX, SyncObjs;
type
{$IFNDEF CONDITIONALEXPRESSIONS}
INT_PTR = Integer;
IInterface = IUnknown;
{$ELSE}
{$IF not declared(INT_PTR)}
INT_PTR = Integer;
{$IFEND}
{$ENDIF}
TAsyncIdleMsgMethod = procedure of object;
{$IFDEF SUPPORT_LOCAL_FUNCTIONS}
TCdeclFunc = Pointer; // function(Arg1: Type1; Arg2: Type2; ...); cdecl;
TCdeclMethod = TMethod; // function(Arg1: Type1; Arg2: Type2; ...) of object; cdecl;
TLocalAsyncProc = function: Integer;
TLocalVclProc = function(Param: INT_PTR): INT_PTR;
TLocalAsyncProcEx = function(Param: INT_PTR): INT_PTR;
//TLocalAsyncForLoopProc = function(Index: Integer; SyncLock: TCriticalSection): Boolean;
{$ENDIF SUPPORT_LOCAL_FUNCTIONS}
TAsyncCallArgObjectProc = function(Arg: TObject): Integer;
TAsyncCallArgIntegerProc = function(Arg: Integer): Integer;
TAsyncCallArgStringProc = function(const Arg: string): Integer;
TAsyncCallArgWideStringProc = function(const Arg: WideString): Integer;
TAsyncCallArgInterfaceProc = function(const Arg: IInterface): Integer;
TAsyncCallArgExtendedProc = function(const Arg: Extended): Integer;
TAsyncCallArgVariantProc = function(const Arg: Variant): Integer;
TAsyncCallArgObjectMethod = function(Arg: TObject): Integer of object;
TAsyncCallArgIntegerMethod = function(Arg: Integer): Integer of object;
TAsyncCallArgStringMethod = function(const Arg: string): Integer of object;
TAsyncCallArgWideStringMethod = function(const Arg: WideString): Integer of object;
TAsyncCallArgInterfaceMethod = function(const Arg: IInterface): Integer of object;
TAsyncCallArgExtendedMethod = function(const Arg: Extended): Integer of object;
TAsyncCallArgVariantMethod = function(const Arg: Variant): Integer of object;
TAsyncCallArgObjectEvent = procedure(Arg: TObject) of object;
TAsyncCallArgIntegerEvent = procedure(Arg: Integer) of object;
TAsyncCallArgStringEvent = procedure(const Arg: string) of object;
TAsyncCallArgWideStringEvent = procedure(const Arg: WideString) of object;
TAsyncCallArgInterfaceEvent = procedure(const Arg: IInterface) of object;
TAsyncCallArgExtendedEvent = procedure(const Arg: Extended) of object;
TAsyncCallArgVariantEvent = procedure(const Arg: Variant) of object;
TAsyncCallArgRecordProc = function(var Arg{: TRecordType}): Integer;
TAsyncCallArgRecordMethod = function(var Arg{: TRecordType}): Integer of object;
TAsyncCallArgRecordEvent = procedure(var Arg{: TRecordType}) of object;
EAsyncCallError = class(Exception);
IAsyncCall = interface
{ Sync() waits until the asynchronous call has finished and returns the
result value of the called function if that exists. }
function Sync: Integer;
{ Finished() returns True if the asynchronous call has finished. }
function Finished: Boolean;
{ ReturnValue() returns the result of the asynchronous call. It raises an
exception if called before the function has finished. It returns 0 if the
AsyncCall invocation was canceled. }
function ReturnValue: Integer;
{ Canceled() returns True if the AsyncCall was canceled by CancelInvocation(). }
function Canceled: Boolean;
{ ForceDifferentThread() tells AsyncCalls that the assigned function must
not be executed in the current thread. }
procedure ForceDifferentThread;
{ CancelInvocation() stopps the AsyncCall from being invoked. If the AsyncCall is already
processed, a call to CancelInvocation() has no effect and the Canceled() function will
return False as the AsyncCall wasn't canceled. }
procedure CancelInvocation;
{ Forget() unlinks the IAsyncCall interface from the internal AsyncCall. This means that
if the last reference to the IAsyncCall interface is gone, the asynchronous call will
be still executed. The interface's methods will throw an exception if called after calling
Forget(). The async function must not call into the main thread because it could be executed
after the TThread.Synchronize/Queue mechanism was shut down by the RTL what can cause a
dead lock. }
procedure Forget;
end;
{ *** Internal interface. Do not use it *** }
IAsyncCallEx = interface
['{A31D8EE4-17B6-4FC7-AC94-77887201EE56}']
function GetEvent: THandle;
function SyncInThisThreadIfPossible: Boolean;
end;
IAsyncRunnable = interface
['{1A313BBD-0F89-43AD-8B57-BBA3205F4888}']
procedure AsyncRun;
end;
{ SetMaxAsyncCallThreads() controls how many threads can be used by the
async call thread pool. The thread pool creates threads when they are needed.
Allocated threads are not destroyed until the application has terminated, but
they are suspended if not used. }
procedure SetMaxAsyncCallThreads(MaxThreads: Integer);
{ GetMaxAsyncCallThreads() returns the maximum number of threads that can
exist in the thread pool. }
function GetMaxAsyncCallThreads: Integer;
{ AsyncCall() executes the given function/procedure in a separate thread. The
result value of the asynchronous function is returned by IAsyncCall.Sync() and
IAsyncCall.ReturnValue().
The AsyncExec() function calls the IdleMsgMethod in a loop, while the async.
method is executed.
Example:
function FileAgeAsync(const Filename: string): Integer;
begin
Result := FileAge(Filename);
end;
var
a: IAsyncCall;
begin
a := AsyncCall(FileAgeAsync, 'C:\Windows\notepad.exe');
// do something
Age := a.Sync;
end;
}
function AsyncCall(Proc: TAsyncCallArgObjectProc; Arg: TObject): IAsyncCall; overload;
function AsyncCall(Proc: TAsyncCallArgIntegerProc; Arg: Integer): IAsyncCall; overload;
function AsyncCall(Proc: TAsyncCallArgStringProc; const Arg: string): IAsyncCall; overload;
function AsyncCall(Proc: TAsyncCallArgWideStringProc; const Arg: WideString): IAsyncCall; overload;
function AsyncCall(Proc: TAsyncCallArgInterfaceProc; const Arg: IInterface): IAsyncCall; overload;
function AsyncCall(Proc: TAsyncCallArgExtendedProc; const Arg: Extended): IAsyncCall; overload;
function AsyncCallVar(Proc: TAsyncCallArgVariantProc; const Arg: Variant): IAsyncCall; overload;
function AsyncCall(Method: TAsyncCallArgObjectMethod; Arg: TObject): IAsyncCall; overload;
function AsyncCall(Method: TAsyncCallArgIntegerMethod; Arg: Integer): IAsyncCall; overload;
function AsyncCall(Method: TAsyncCallArgStringMethod; const Arg: string): IAsyncCall; overload;
function AsyncCall(Method: TAsyncCallArgWideStringMethod; const Arg: WideString): IAsyncCall; overload;
function AsyncCall(Method: TAsyncCallArgInterfaceMethod; const Arg: IInterface): IAsyncCall; overload;
function AsyncCall(Method: TAsyncCallArgExtendedMethod; const Arg: Extended): IAsyncCall; overload;
function AsyncCallVar(Method: TAsyncCallArgVariantMethod; const Arg: Variant): IAsyncCall; overload;
function AsyncCall(Method: TAsyncCallArgObjectEvent; Arg: TObject): IAsyncCall; overload;
function AsyncCall(Method: TAsyncCallArgIntegerEvent; Arg: Integer): IAsyncCall; overload;
function AsyncCall(Method: TAsyncCallArgStringEvent; const Arg: string): IAsyncCall; overload;
function AsyncCall(Method: TAsyncCallArgWideStringEvent; const Arg: WideString): IAsyncCall; overload;
function AsyncCall(Method: TAsyncCallArgInterfaceEvent; const Arg: IInterface): IAsyncCall; overload;
function AsyncCall(Method: TAsyncCallArgExtendedEvent; const Arg: Extended): IAsyncCall; overload;
function AsyncCallVar(Method: TAsyncCallArgVariantEvent; const Arg: Variant): IAsyncCall; overload;
function AsyncCall(Runnable: IAsyncRunnable): IAsyncCall; overload;
procedure AsyncExec(Method: TNotifyEvent; Arg: TObject; IdleMsgMethod: TAsyncIdleMsgMethod);
{$IFDEF SUPPORT_LOCAL_FUNCTIONS}
{ LocalAsyncCall() executes the given local function/procedure in a separate thread.
The result value of the asynchronous function is returned by IAsyncCall.Sync() and
IAsyncCall.ReturnValue().
The LocalAsyncExec() function calls the IdleMsgMethod while the local procedure is
executed.
Example:
procedure MainProc(const S: string);
var
Value: Integer;
a: IAsyncCall;
function DoSomething: Integer;
begin
if S = 'Abc' then
Value := 1;
Result := 0;
end;
begin
a := LocalAsyncCall(@DoSomething);
// do something
a.Sync;
LocalAsyncExec(@DoSomething, Application.ProcessMessages);
end;
}
function LocalAsyncCall(LocalProc: TLocalAsyncProc): IAsyncCall;
function LocalAsyncCallEx(LocalProc: TLocalAsyncProcEx; Param: INT_PTR): IAsyncCall;
procedure LocalAsyncExec(Proc: TLocalAsyncProc; IdleMsgMethod: TAsyncIdleMsgMethod);
{ LocalVclCall() executes the given local function/procedure in the main thread. It
uses the TThread.Synchronize function which blocks the current thread.
LocalAsyncVclCall() execute the given local function/procedure in the main thread.
It does not wait for the main thread to execute the function unless the current
thread is the main thread. In that case it executes and waits for the specified
function in the current thread like LocalVclCall().
The result value of the asynchronous function is returned by IAsyncCall.Sync() and
IAsyncCall.ReturnValue().
Example:
procedure TForm1.MainProc;
procedure DoSomething;
procedure UpdateProgressBar(Percentage: Integer);
begin
ProgressBar.Position := Percentage;
Sleep(20); // This delay does not affect the time for the 0..100 loop
// because UpdateProgressBar is non-blocking.
end;
procedure Finished;
begin
ShowMessage('Finished');
end;
var
I: Integer;
begin
for I := 0 to 100 do
begin
// Do some time consuming stuff
Sleep(30);
LocalAsyncVclCall(@UpdateProgressBar, I); // non-blocking
end;
LocalVclCall(@Finished); // blocking
end;
var
a: IAsyncCall;
begin
a := LocalAsyncCall(@DoSomething);
a.ForceDifferentThread; // Do not execute in the main thread because this will
// change LocalAyncVclCall into a blocking LocalVclCall
// do something
//a.Sync; The Compiler will call this for us in the Interface._Release method
end;
}
procedure LocalVclCall(LocalProc: TLocalVclProc; Param: INT_PTR = 0);
function LocalAsyncVclCall(LocalProc: TLocalVclProc; Param: INT_PTR = 0): IAsyncCall;
{$ENDIF SUPPORT_LOCAL_FUNCTIONS}
{ AsyncCallEx() executes the given function/procedure in a separate thread. The
Arg parameter can be a record type. The fields of the record can be modified
in the asynchon function.
Example:
type
TData = record
Value: Integer;
end;
procedure TestRec(var Data: TData);
begin
Data.Value := 70;
end;
a := AsyncCallEx(@TestRec, MyData);
a.Sync; // MyData.Value is now 70
}
function AsyncCallEx(Proc: TAsyncCallArgRecordProc; var Arg{: TRecordType}): IAsyncCall; overload;
function AsyncCallEx(Method: TAsyncCallArgRecordMethod; var Arg{: TRecordType}): IAsyncCall; overload;
function AsyncCallEx(Method: TAsyncCallArgRecordEvent; var Arg{: TRecordType}): IAsyncCall; overload;
{$IFDEF SUPPORT_LOCAL_FUNCTIONS}
{ The following AsyncCall() functions support variable parameters. All reference
counted types are protected by an AddRef and later Release. The ShortString,
Extended, Currency and Int64 types are internally copied to a temporary location.
Supported types:
Integer : Arg: Integer
Boolean : Arg: Boolean
Char : Arg: AnsiChar
WideChar : Arg: WideChar
Int64 : [const] Arg: Int64
Extended : [const] Arg: Extended
Currency : [const] Arg: Currency
String : [const] Arg: ShortString
Pointer : [const] Arg: Pointer
PChar : [const] Arg: PChar
Object : [const] Arg: TObject
Class : [const] Arg: TClass
AnsiString : [const] Arg: AnsiString
UnicodeString: [const] Arg: UnicodeString
PWideChar : [const] Arg: PWideChar
WideString : [const] Arg: WideString
Interface : [const] Arg: IInterface
Variant : const Arg: Variant
Example:
procedure Test(const S: string; I: Integer; E: Extended; Obj: TObject); cdecl;
begin
end;
AsyncCall(@Test, ['Hallo', 10, 3.5, MyObject]);
}
function AsyncCall(Proc: TCdeclFunc; const Args: array of const): IAsyncCall; overload;
function AsyncCall(Proc: TCdeclMethod; const Args: array of const): IAsyncCall; overload;
{$ENDIF SUPPORT_LOCAL_FUNCTIONS}
{ AsyncMultiSync() waits for the async calls and other handles to finish.
MsgAsyncMultiSync() waits for the async calls, other handles and the message queue.
Arguments:
List : An array of IAsyncCall interfaces for which the function
should wait.
Handles : An array of THandle for which the function should wait.
WaitAll = True : The function returns when all listed async calls have
finished. If Milliseconds is INFINITE the async calls
meight be executed in the current thread.
The return value is zero when all async calls have finished.
Otherwise it is -1.
WaitAll = False : The function returns when at least one of the async calls
has finished. The return value is the list index of the
first finished async call. If there was a timeout, the
return value is -1.
Milliseconds : Specifies the number of milliseconds to wait until a
timeout happens. The value INFINITE lets the function wait
until all async calls have finished.
dwWakeMask : see Windows.MsgWaitForMultipleObjects()
Limitations:
Length(List)+Length(Handles) must not exceed MAXIMUM_ASYNC_WAIT_OBJECTS.
Return value:
WAIT_TIMEOUT
The function timed out
WAIT_OBJECT_0+index
The first finished async call
WAIT_OBJECT_0+Length(List)+index
The first signaled handle
WAIT_OBJECT_0+Length(List)+Length(Handles)
A message was signaled
WAIT_ABANDONED_0+index
The abandoned async call
WAIT_ABANDONED_0+Length(List)+index
The abandoned handle
WAIT_FAILED
The function failed
}
const
MAXIMUM_ASYNC_WAIT_OBJECTS = MAXIMUM_WAIT_OBJECTS - 3;
function AsyncMultiSync(const List: array of IAsyncCall; WaitAll: Boolean = True;
Milliseconds: Cardinal = INFINITE): Cardinal;
function AsyncMultiSyncEx(const List: array of IAsyncCall; const Handles: array of THandle;
WaitAll: Boolean = True; Milliseconds: Cardinal = INFINITE): Cardinal;
function MsgAsyncMultiSync(const List: array of IAsyncCall; WaitAll: Boolean;
Milliseconds: Cardinal; dwWakeMask: DWORD): Cardinal;
function MsgAsyncMultiSyncEx(const List: array of IAsyncCall; const Handles: array of THandle;
WaitAll: Boolean; Milliseconds: Cardinal; dwWakeMask: DWORD): Cardinal;
{$IFDEF SUPPORT_LOCAL_FUNCTIONS}
{
EnterMainThread/LeaveMainThread can be used to temporary switch to the
main thread. The code that should be synchonized (blocking) has to be put
into a try/finally block and the LeaveMainThread() function must be called
from the finally block. A missing try/finally will lead to an access violation.
* All local variables can be used. (EBP points to the thread's stack while
ESP points the the main thread's stack)
* Unhandled exceptions are passed to the surrounding thread.
* The integrated Debugger is not able to follow the execution flow. You have
to use break points instead of "Step over/in".
* Nested calls to EnterMainThread/LeaveMainThread are ignored. But they must
strictly follow the try/finally structure.
Example:
procedure MyThreadProc;
var
S: string;
begin
Assert(GetCurrentThreadId <> MainThreadId);
S := 'Hallo, I''m executed in the main thread';
EnterMainThread;
try
Assert(GetCurrentThreadId = MainThreadId);
ShowMessage(S);
finally
LeaveMainThread;
end;
Assert(GetCurrentThreadId <> MainThreadId);
end;
}
procedure EnterMainThread;
procedure LeaveMainThread;
{$ENDIF SUPPORT_LOCAL_FUNCTIONS}
type
TAsyncCall = class;
{ *** Internal class. Do not use it *** }
{ TAsyncCall is the base class for all parameter based async call types }
TInternalAsyncCall = class(TObject)
private
FNext: TInternalAsyncCall;
FEvent: THandle;
FReturnValue: Integer;
FFinished: Boolean;
FFatalException: Exception;
FFatalErrorAddr: Pointer;
FForceDifferentThread: Boolean;
FCancelInvocation: Boolean;
FCanceled: Boolean;
FExecuted: Boolean;
FAutoDelete: Boolean;
procedure InternExecuteAsyncCall;
procedure InternExecuteSyncCall;
procedure Quit(AReturnValue: Integer);
protected
{ Decendants must implement this method. It is called when the async call
should be executed. }
function ExecuteAsyncCall: Integer; virtual; abstract;
private
constructor Create;
function ExecuteAsync: TAsyncCall;
function GetEvent: THandle;
function SyncInThisThreadIfPossible: Boolean;
function Sync: Integer;
function Finished: Boolean;
function ReturnValue: Integer;
function Canceled: Boolean;
procedure ForceDifferentThread;
procedure CancelInvocation;
procedure Forget;
public
destructor Destroy; override;
end;
{ *** Internal class. Do not use it *** }
TAsyncCall = class(TInterfacedObject, IAsyncCall, IAsyncCallEx)
private
FCall: TInternalAsyncCall;
procedure CheckForget;
{ IAsyncCallEx }
function GetEvent: THandle;
function SyncInThisThreadIfPossible: Boolean;
private
constructor Create(ACall: TInternalAsyncCall);
{ IAsyncCall }
function Sync: Integer;
function Finished: Boolean;
function ReturnValue: Integer;
function Canceled: Boolean;
procedure ForceDifferentThread;
procedure CancelInvocation;
procedure Forget;
public
destructor Destroy; override;
end;
{ *** Internal class. Do not use it *** }
{ TSyncCall is a fake IAsyncCall implementor. The async call was already
executed when the interface is returned. }
TSyncCall = class(TInterfacedObject, IAsyncCall)
private
FReturnValue: Integer;
private
constructor Create(AReturnValue: Integer);
function Sync: Integer;
function Finished: Boolean;
function ReturnValue: Integer;
function Canceled: Boolean;
procedure ForceDifferentThread;
procedure CancelInvocation;
procedure Forget;
end;
{$IFDEF DELPHI2009_UP}
type
{ *** Helper class *** }
TMultiArgProcCall<TProc, T1> = class(TInternalAsyncCall)
private
FProc: TProc;
FArg1: T1;
public
constructor Create(AProc: TProc; const AArg1: T1);
end;
TMultiArgProcCall<TProc, T1, T2> = class(TMultiArgProcCall<TProc, T1>)
private
FArg2: T2;
public
constructor Create(AProc: TProc; const AArg1: T1; const AArg2: T2);
end;
TMultiArgProcCall<TProc, T1, T2, T3> = class(TMultiArgProcCall<TProc, T1, T2>)
private
FArg3: T3;
public
constructor Create(AProc: TProc; const AArg1: T1; const AArg2: T2; const AArg3: T3);
end;
TMultiArgProcCall<TProc, T1, T2, T3, T4> = class(TMultiArgProcCall<TProc, T1, T2, T3>)
private
FArg4: T4;
public
constructor Create(AProc: TProc; const AArg1: T1; const AArg2: T2; const AArg3: T3; const AArg4: T4);
end;
TAsyncCalls = class(TObject)
private
type
TAsyncCallArgGenericProc<T> = function(Arg: T): Integer;
TAsyncCallArgGenericProc<T1, T2> = function(Arg1: T1; Arg2: T2): Integer;
TAsyncCallArgGenericProc<T1, T2, T3> = function(Arg1: T1; Arg2: T2; Arg3: T3): Integer;
TAsyncCallArgGenericProc<T1, T2, T3, T4> = function(Arg1: T1; Arg2: T2; Arg3: T3; Arg4: T4): Integer;
TAsyncCallArgGenericMethod<T> = function(Arg: T): Integer of object;
TAsyncCallArgGenericMethod<T1, T2> = function(Arg1: T1; Arg2: T2): Integer of object;
TAsyncCallArgGenericMethod<T1, T2, T3> = function(Arg1: T1; Arg2: T2; Arg3: T3): Integer of object;
TAsyncCallArgGenericMethod<T1, T2, T3, T4> = function(Arg1: T1; Arg2: T2; Arg3: T3; Arg4: T4): Integer of object;
TIntFunc = reference to function: Integer;
TAsyncCallArg<T> = class(TMultiArgProcCall<TAsyncCallArgGenericProc<T>, T>)
protected
function ExecuteAsyncCall: Integer; override;
end;
TAsyncCallArg<T1, T2> = class(TMultiArgProcCall<TAsyncCallArgGenericProc<T1, T2>, T1, T2>)
protected
function ExecuteAsyncCall: Integer; override;
end;
TAsyncCallArg<T1, T2, T3> = class(TMultiArgProcCall<TAsyncCallArgGenericProc<T1, T2, T3>, T1, T2, T3>)
protected
function ExecuteAsyncCall: Integer; override;
end;
TAsyncCallArg<T1, T2, T3, T4> = class(TMultiArgProcCall<TAsyncCallArgGenericProc<T1, T2, T3, T4>, T1, T2, T3, T4>)
protected
function ExecuteAsyncCall: Integer; override;
end;
TAsyncCallArgMethod<T> = class(TMultiArgProcCall<TAsyncCallArgGenericMethod<T>, T>)
protected
function ExecuteAsyncCall: Integer; override;
end;
TAsyncCallArgMethod<T1, T2> = class(TMultiArgProcCall<TAsyncCallArgGenericMethod<T1, T2>, T1, T2>)
protected
function ExecuteAsyncCall: Integer; override;
end;
TAsyncCallArgMethod<T1, T2, T3> = class(TMultiArgProcCall<TAsyncCallArgGenericMethod<T1, T2, T3>, T1, T2, T3>)
protected
function ExecuteAsyncCall: Integer; override;
end;
TAsyncCallArgMethod<T1, T2, T3, T4> = class(TMultiArgProcCall<TAsyncCallArgGenericMethod<T1, T2, T3, T4>, T1, T2, T3, T4>)
protected
function ExecuteAsyncCall: Integer; override;
end;
TAsyncCallAnonymProc = class(TInternalAsyncCall)
private
FProc: TProc;
protected
function ExecuteAsyncCall: Integer; override;
public
constructor Create(AProc: TProc);
end;
TAsyncCallAnonymFunc = class(TInternalAsyncCall)
private
FProc: TIntFunc;
protected
function ExecuteAsyncCall: Integer; override;
public
constructor Create(AProc: TIntFunc);
end;
TAsyncVclCallAnonymProc = class(TInternalAsyncCall)
private
FProc: TProc;
protected
function ExecuteAsyncCall: Integer; override;
public
constructor Create(AProc: TProc);
end;
public
{ Invoke an asynchronous function call }
class function Invoke<T>(Proc: TAsyncCallArgGenericProc<T>; const Arg: T): IAsyncCall; overload; static;
class function Invoke<T>(Event: TAsyncCallArgGenericMethod<T>; const Arg: T): IAsyncCall; overload; static;
class function Invoke<T1, T2>(Proc: TAsyncCallArgGenericProc<T1, T2>; const Arg1: T1; const Arg2: T2): IAsyncCall; overload; static;
class function Invoke<T1, T2>(Event: TAsyncCallArgGenericMethod<T1, T2>; const Arg1: T1; const Arg2: T2): IAsyncCall; overload; static;
class function Invoke<T1, T2, T3>(Proc: TAsyncCallArgGenericProc<T1, T2, T3>; const Arg1: T1; const Arg2: T2; const Arg3: T3): IAsyncCall; overload; static;
class function Invoke<T1, T2, T3>(Event: TAsyncCallArgGenericMethod<T1, T2, T3>; const Arg1: T1; const Arg2: T2; const Arg3: T3): IAsyncCall; overload; static;
class function Invoke<T1, T2, T3, T4>(Proc: TAsyncCallArgGenericProc<T1, T2, T3, T4>; const Arg1: T1; const Arg2: T2; const Arg3: T3; const Arg4: T4): IAsyncCall; overload; static;
class function Invoke<T1, T2, T3, T4>(Event: TAsyncCallArgGenericMethod<T1, T2, T3, T4>; const Arg1: T1; const Arg2: T2; const Arg3: T3; const Arg4: T4): IAsyncCall; overload; static;
{ Invoke an asynchronous anonymous method call }
class function Invoke(Func: TIntFunc): IAsyncCall; overload; static;
class function Invoke(Proc: TProc): IAsyncCall; overload; static;
{ MsgExec waits for the @AsyncCall to finish. If there are any messages in
the message queue and the function was called from the main thread, it will
call @IdleMsgMethod. "Application.ProcessMessages" can be specified for
@IdleMsgMethod. }
class procedure MsgExec(AsyncCall: IAsyncCall; IdleMsgMethod: TAsyncIdleMsgMethod); static;
{ Synchronize with the VCL }
{ VCLSync returns when the anonymous method was called in the main thread }
class procedure VCLSync(Proc: TProc); static;
{ VCLInvoke returns immediately. The anonymous method will be executed in
the main thread. }
class function VCLInvoke(Proc: TProc): IAsyncCall; static;
end;
{$ENDIF DELPHI2009_UP}
implementation
{$IFDEF DELPHI5}
uses
Forms; // AllocateHWnd
{$ENDIF DELPHI5}
resourcestring
RsAsyncCallNotFinished = 'The asynchronous call is not finished yet';
RsAsyncCallUnknownVarRecType = 'Unknown TVarRec type %d';
RsLeaveMainThreadNestedError = 'Unpaired call to AsyncCalls.LeaveMainThread()';
RsLeaveMainThreadThreadError = 'AsyncCalls.LeaveMainThread() was called outside of the main thread';
RsForgetWasCalled = 'IAsyncCall.Forget was called. The interface isn''t connected to the asynchronous call anymore';
RsNoVclSyncPossible = 'Cannot synchronize with the main thread anymore. Don''t call IAsyncCall.Forget for functions that access the VCL';
const
WM_VCLSYNC = WM_USER + 12;
{$IFNDEF DELPHI7_UP}
var
SyncEvent: THandle;
type
TThread = class(Classes.TThread)
{$IFDEF DELPHI6}
private
class procedure WakeMainThread(Sender: TObject);
{$ENDIF DELPHI6}
public
class procedure StaticSynchronize(AThread: TThread; AMethod: TThreadMethod);
end;
class procedure TThread.StaticSynchronize(AThread: TThread; AMethod: TThreadMethod);
var
Obj: TThread;
begin
if GetCurrentThreadId = MainThreadId then
AMethod
else if AThread <> nil then
AThread.Synchronize(AMethod)
else
begin
{$WARNINGS OFF} // suppress abstract class warning
Obj := TThread.Create(True);
{$WARNINGS ON}
try
Obj.Synchronize(AMethod);
finally
Obj.Free;
end;
end;
end;
{$ENDIF ~DELPHI7_UP}
procedure StaticSynchronize(AMethod: TThreadMethod);
begin
{$IFDEF DELPHI2010_UP}
TThread.Synchronize(nil, AMethod);
{$ELSE}
TThread.StaticSynchronize(nil, AMethod);
{$ENDIF DELPHI2010_UP}
end;
{$IFDEF DELPHI5}
function CheckSynchronize(Timeout: Integer = 0): Boolean;
begin
Result := False;
end;
function AcquireExceptionObject: Pointer;
type
PRaiseFrame = ^TRaiseFrame;
TRaiseFrame = record
NextRaise: PRaiseFrame;
ExceptAddr: Pointer;
ExceptObject: TObject;
ExceptionRecord: PExceptionRecord;
end;
begin
if RaiseList <> nil then
begin
Result := PRaiseFrame(RaiseList)^.ExceptObject;
PRaiseFrame(RaiseList)^.ExceptObject := nil;
end
else
Result := nil;
end;
{$ENDIF DELPHI5}
{$IFDEF DELPHI6}
var
OrgWakeMainThread: TNotifyEvent;
class procedure TThread.WakeMainThread(Sender: TObject);
begin
if Assigned(OrgWakeMainThread) then
OrgWakeMainThread(Sender);
SetEvent(SyncEvent);
end;
procedure HookWakeMainThread;
begin
OrgWakeMainThread := Classes.WakeMainThread;
Classes.WakeMainThread := TThread.WakeMainThread;
end;
procedure UnhookWakeMainThread;
begin
Classes.WakeMainThread := OrgWakeMainThread;
end;
{$ENDIF DELPHI6}
{$IFNDEF DELPHI2009_UP}
// Needed for older Delphi versions
function InterlockedCompareExchange(var Destination: Integer; Exchange: Integer; Comparand: Integer): Integer;
asm
XCHG EAX, ECX
LOCK CMPXCHG [ECX], EDX
end;
{$ENDIF ~DELPHI2009_UP}
type
{ TAsyncCallThread is a pooled thread. It looks itself for work. }
TAsyncCallThread = class(TThread)
{$IFDEF DEBUG_THREADSTATS}
private
FTaskCount: Integer;
FTaskTime: Int64;
{$ENDIF DEBUG_THREADSTATS}
protected
procedure Execute; override;
public
constructor Create(ACreateSuspended: Boolean);
end;
{ TThreadPool contains a pool of threads that are either suspended or busy. }
TThreadPool = class(TObject)
private
FWakeUpEvent: THandle;
FThreadTerminateEvent: THandle;
FSleepingThreadCount: Integer;
FMaxThreads: Integer;
FDestroying: Boolean;
FThreadCount: Integer;
FThreads: array[0..255] of TAsyncCallThread;
FAsyncCallsCritSect: TRTLCriticalSection;
FAsyncCallHead, FAsyncCallTail: TInternalAsyncCall;
FAutoDeleteAsyncCalls: TInternalAsyncCall;
FNumberOfProcessors: Cardinal;
{$IFDEF DEBUG_THREADSTATS}
FSyncExecutedCount, FAsyncExecutedCount: Integer;
{$ENDIF DEBUG_THREADSTATS}
FMainThreadSyncEvent: THandle;
FMainThreadVclHandle: HWND;
procedure MainThreadWndProc(var Msg: TMessage);
procedure ProcessMainThreadSync;
procedure AllocThread;
function GetNextAsyncCall: TInternalAsyncCall; // called from the threads
procedure WakeUpThread;
procedure Sleep;
procedure ReleaseAutoDeleteAsyncCalls;
procedure CheckAutoDelete(Call: TInternalAsyncCall);
public
constructor Create;
destructor Destroy; override;
procedure CheckDestroying;
procedure SendVclSync(Call: TInternalAsyncCall);
procedure AddAsyncCall(Call: TInternalAsyncCall);
function RemoveAsyncCall(Call: TInternalAsyncCall): Boolean;
procedure ForgetAsyncCall(Call: TInternalAsyncCall);
property MaxThreads: Integer read FMaxThreads;
property NumberOfProcessors: Cardinal read FNumberOfProcessors;
property MainThreadSyncEvent: THandle read FMainThreadSyncEvent;
end;
{ ---------------------------------------------------------------------------- }
TAsyncCallArgObject = class(TInternalAsyncCall)
private
FProc: TAsyncCallArgObjectProc;
FArg: TObject;
protected
function ExecuteAsyncCall: Integer; override;
public
constructor Create(AProc: TAsyncCallArgObjectProc; AArg: TObject);
end;
TAsyncCallArgString = class(TInternalAsyncCall)
private
FProc: TAsyncCallArgStringProc;
FArg: string;
protected
function ExecuteAsyncCall: Integer; override;
public
constructor Create(AProc: TAsyncCallArgStringProc; const AArg: string);
end;
TAsyncCallArgWideString = class(TInternalAsyncCall)
private
FProc: TAsyncCallArgWideStringProc;
FArg: WideString;
protected
function ExecuteAsyncCall: Integer; override;
public
constructor Create(AProc: TAsyncCallArgWideStringProc; const AArg: WideString);
end;
TAsyncCallArgInterface = class(TInternalAsyncCall)
private
FProc: TAsyncCallArgInterfaceProc;
FArg: IInterface;
protected
function ExecuteAsyncCall: Integer; override;