Menu

[r3207]: / trunk / Src / UWaitForThreadUI.pas  Maximize  Restore  History

Download this file

394 lines (358 with data), 13.2 kB

  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
{
* This Source Code Form is subject to the terms of the Mozilla Public License,
* v. 2.0. If a copy of the MPL was not distributed with this file, You can
* obtain one at http://mozilla.org/MPL/2.0/
*
* Copyright (C) 2006-2013, Peter Johnson (www.delphidabbler.com).
*
* $Rev$
* $Date$
*
* Implements a class that executes a thread and displays a dialog box if thread
* takes more than a specified time to complete.
}
unit UWaitForThreadUI;
interface
uses
// Delphi
SysUtils, Classes, ExtCtrls, Forms, SyncObjs,
// Project
UBaseObjects;
type
{
TWaitForThreadUI:
Class that executes a thread and displays a dialog box if thread takes more
than a specified time to complete.
}
TWaitForThreadUI = class(TNoPublicConstructObject)
strict private
const DefaultPauseBeforeDisplay = 50;
const DefaultMinDisplayTime = 1000;
var fThread: TThread; // Thread to be executed
var fForm: TForm; // Form to be displayed if required
var fMinDisplayTimer: TTimer; // Timer to delay closure of form
var fSaveOnTerminate: TNotifyEvent; // Saves fThread.OnTerminate value
var fSaveFormShow: TNotifyEvent; // Saves fForm.OnShow value
var fFormCloseRequested: Boolean; // Indicates if form is awaiting closure
var fPauseBeforeDisplay: Cardinal; // Time before fForm is displayed
var fThreadTerminated: Boolean; // Indicates if fThread has terminated
var fMinTimeElapsed: Boolean; // True when form displayed long enough
class var fLock: TCriticalSection; // Protects form opening / closing
procedure ThreadTerminated(Sender: TObject);
{Handles thread's OnTerminate event. Flags thread has terminated and
requests closure of any displayed form.
@param Sender [in] Not used.
}
procedure MinTimeElapsed(Sender: TObject);
{Timer event handler called once, when minimum execution time has elapsed.
@param Sender [in] Not used.
}
procedure ShowForm;
{Displays required form. A critical section ensures that only one thread
at a time can attempt to show the form.
}
procedure CloseForm;
{Closes any displayed form if thread has terminated and minimum display
time has elapsed. A critical section ensures that only one thread at a
time can attempt to close the form.
}
procedure FormShowHandler(Sender: TObject);
{Event handler for fForm.OnShow event. Checks if form can open.
@param Sender [in] Reference to form triggering event.
}
procedure Pause;
{Delays execution by fPauseBeforeDisplay ms.
}
strict protected
constructor InternalCreate(const AThread: TThread;
const AForm: TForm; const APauseBeforeDisplay, AMinDisplayTime: Cardinal);
{Object constructor. Sets up object.
@param AThread [in] Thread to be executed.
@param AForm [in] Form to be displayed while thread executes.
@param APauseBeforeDisplay [in] Time thread given to execute before form
is displayed (optional)
@param AMinDisplayTime [in] Minimum time to display form (optional).
}
procedure Execute;
{Executes thread and displays dialog box if necessary.
}
public
class constructor Create;
{Class constructor. Initialises critical section.
}
class destructor Destroy;
{Class destructor. Destroys critical section.
}
destructor Destroy; override;
{Object destructor. Tears down object.
}
class procedure Run(const AThread: TThread; const AForm: TForm;
const APauseBeforeDisplay: Cardinal = DefaultPauseBeforeDisplay;
const AMinDisplayTime: Cardinal = DefaultMinDisplayTime); overload;
{Creates and executes a TWaitForThreadUI object that executes a thread,
displaying dialog box if necessary.
@param AThread [in] Thread to be executed.
@param AForm [in] Form to be displayed while thread executes.
@param APauseBeforeDisplay [in] Time thread given to execute before form
is displayed (optional)
@param AMinDisplayTime [in] Minimum time to display form (optional).
}
class procedure Run(const AProc: TProc; const AIsThreadSafe: Boolean;
const AForm: TForm;
const APauseBeforeDisplay: Cardinal = DefaultPauseBeforeDisplay;
const AMinDisplayTime: Cardinal = DefaultMinDisplayTime); overload;
{Creates and executes a TWaitForThreadUI object that executes a closure in
a thread, displaying dialog box if necessary.
@param AProc [in] Closure to be executed in thread.
@param AIsThreadSage [in] Indicates if AProc is thread safe. If True
AProc is excuted in context of thread. If False closure is executed
in context of main thread.
@param AForm [in] Form to be displayed while thread executes.
@param APauseBeforeDisplay [in] Time thread given to execute before form
is displayed (optional)
@param AMinDisplayTime [in] Minimum time to display form (optional).
}
end;
implementation
uses
// Project
UExceptions, UUtils;
type
/// <summary>Thread class that executes a given closure.</summary>
TProcThread = class(TThread)
strict private
var
/// <summary>Closure to executed.</summary>
fProc: TProc;
/// <summary>Flag indicating if closure is thread safe.</summary>
fProcIsThreadSafe: Boolean;
strict protected
/// <summary>Executes closure from thread.</summary>
procedure Execute; override;
public
/// <summary>Constructs a new, suspended, thread instance.</summary>
/// <param name="Proc">TProc [in] Closure to be executed by thread.</param>
/// <param name="ProcIsThreadSafe">Boolean [in] Flag indicating if Proc is
/// thread safe or not.</param>
/// <remarks>If Proc is not thread safe it is executed in the context of
/// the main thread.</remarks>
constructor Create(const Proc: TProc; const ProcIsThreadSafe: Boolean);
end;
{ TWaitForThreadUI }
procedure TWaitForThreadUI.CloseForm;
{Closes any displayed form if thread has terminated and minimum display time
has elapsed. A critical section ensures that only one thread at a time can
attempt to close the form.
}
begin
fLock.Acquire;
try
if not Assigned(fForm) then
Exit;
fFormCloseRequested := fThreadTerminated and fMinTimeElapsed;
if fFormCloseRequested and fForm.Visible then
fForm.Close;
finally
fLock.Release;
end;
end;
class constructor TWaitForThreadUI.Create;
{Class constructor. Initialises critical section.
}
begin
fLock := TCriticalSection.Create;
end;
destructor TWaitForThreadUI.Destroy;
{Object destructor. Tears down object.
}
begin
fMinDisplayTimer.Free;
fThread.OnTerminate := fSaveOnTerminate;
inherited;
end;
class destructor TWaitForThreadUI.Destroy;
{Class destructor. Destroys critical section.
}
begin
fLock.Free;
end;
procedure TWaitForThreadUI.Execute;
{Executes thread and displays dialog box if necessary.
}
begin
// Flag that form closure not yet requested
fFormCloseRequested := False;
// Reset termination flags
fThreadTerminated := False;
fMinTimeElapsed := False;
// Execute thread
fThread.OnTerminate := ThreadTerminated;
fThread.Start;
// Pause before displayng dialog by PauseBeforeDisplay ms
Pause;
if not fThread.Finished then
// Show dialog if thread not completed. Dialog blocks until thread
// terminates.
ShowForm;
// Re-raise any exception that was raised by thread: must be a clone and not
// the original exception.
if Assigned(fThread.FatalException)
and (fThread.FatalException is Exception) then
raise TExceptionHelper.Clone(fThread.FatalException as Exception);
end;
procedure TWaitForThreadUI.FormShowHandler(Sender: TObject);
{Event handler for fForm.OnShow event. Checks if form can open.
@param Sender [in] Reference to form triggering event.
}
begin
// Call any earler OnShow handler for form
if Assigned(fSaveFormShow) then
fSaveFormShow(Sender);
// If form has already been requested to close then close it
if fFormCloseRequested then
fForm.Close;
end;
constructor TWaitForThreadUI.InternalCreate(const AThread: TThread;
const AForm: TForm; const APauseBeforeDisplay, AMinDisplayTime: Cardinal);
{Object constructor. Sets up object.
@param AThread [in] Thread to be executed.
@param AForm [in] Form to be displayed while thread executes.
@param APauseBeforeDisplay [in] Time thread given to execute before form is
displayed (optional)
@param AMinDisplayTime [in] Minimum time to display form (optional).
}
begin
inherited InternalCreate;
// Set up timer that triggers event when form can close
fMinDisplayTimer := TTimer.Create(nil);
fMinDisplayTimer.Enabled := False;
fMinDisplayTimer.OnTimer := MinTimeElapsed;
fMinDisplayTimer.Interval := AMinDisplayTime;
// Record other fields
fPauseBeforeDisplay := APauseBeforeDisplay;
fThread := AThread;
fSaveOnTerminate := AThread.OnTerminate;
fForm := AForm;
end;
procedure TWaitForThreadUI.MinTimeElapsed(Sender: TObject);
{Timer event handler called once, when minimum execution time has elapsed.
@param Sender [in] Not used.
}
begin
// Switch off timer
fMinDisplayTimer.OnTimer := nil;
fMinDisplayTimer.Enabled := False;
fMinTimeElapsed := True;
// Close form
CloseForm;
end;
procedure TWaitForThreadUI.Pause;
{Delays execution by fPauseBeforeDisplay ms.
}
begin
if fPauseBeforeDisplay = 0 then
Exit;
// Busy wait
UUtils.Pause(fPauseBeforeDisplay);
end;
class procedure TWaitForThreadUI.Run(const AProc: TProc;
const AIsThreadSafe: Boolean; const AForm: TForm;
const APauseBeforeDisplay, AMinDisplayTime: Cardinal);
{Creates and executes a TWaitForThreadUI object that executes a closure in a
thread, displaying dialog box if necessary.
@param AProc [in] Closure to be executed in thread.
@param AIsThreadSage [in] Indicates if AProc is thread safe. If True AProc
is excuted in context of thread. If False closure is executed in context
of main thread.
@param AForm [in] Form to be displayed while thread executes.
@param APauseBeforeDisplay [in] Time thread given to execute before form is
displayed (optional)
@param AMinDisplayTime [in] Minimum time to display form (optional).
}
var
ProcThread: TProcThread; // thread used to execute AProc
begin
ProcThread := TProcThread.Create(AProc, AIsThreadSafe);
try
Run(ProcThread, AForm, APauseBeforeDisplay, AMinDisplayTime);
finally
ProcThread.Free;
end;
end;
class procedure TWaitForThreadUI.Run(const AThread: TThread;
const AForm: TForm; const APauseBeforeDisplay, AMinDisplayTime: Cardinal);
{Creates and executes a TWaitForThreadUI object that executes a thread,
displaying dialog box if necessary.
@param AThread [in] Thread to be executed.
@param AForm [in] Form to be displayed while thread executes.
@param APauseBeforeDisplay [in] Time thread given to execute before form is
displayed (optional)
@param AMinDisplayTime [in] Minimum time to display form (optional).
}
begin
Assert(Assigned(AThread), ClassName + '.Run: AThread is nil');
with InternalCreate(AThread, AForm, APauseBeforeDisplay, AMinDisplayTime) do
try
Execute;
finally
Free;
end;
end;
procedure TWaitForThreadUI.ShowForm;
{Displays required form. A critical section ensures that only one thread at a
time can attempt to show the form.
}
begin
fLock.Acquire;
try
if not Assigned(fForm) then
Exit;
// Start timer that triggers when form is allowed to close after minimum
// display time. If time is zero we need to trigger ourselves, because
// timer won't fire.
fMinDisplayTimer.Enabled := True;
if fMinDisplayTimer.Interval = 0 then
MinTimeElapsed(fMinDisplayTimer);
// Store any existing OnShow event of form and replace with our handler
fSaveFormShow := fForm.OnShow;
fForm.OnShow := FormShowHandler;
try
// Show form modally if not already requested to close
if not fFormCloseRequested then
fForm.ShowModal;
finally
// Restore any previous OnShow event handler
fForm.OnShow := fSaveFormShow;
end;
finally
fLock.Release;
end;
end;
procedure TWaitForThreadUI.ThreadTerminated(Sender: TObject);
{Handles thread's OnTerminate event. Flags thread has terminated and requests
closure of any displayed form.
@param Sender [in] Not used.
}
begin
fThreadTerminated := True;
CloseForm;
if Assigned(fSaveOnTerminate) then
fSaveOnTerminate(fThread);
end;
{ TProcThread }
constructor TProcThread.Create(const Proc: TProc;
const ProcIsThreadSafe: Boolean);
begin
Assert(Assigned(Proc), ClassName + '.Create: Proc is nil');
inherited Create(True);
fProc := Proc;
fProcIsThreadSafe := ProcIsThreadSafe;
end;
procedure TProcThread.Execute;
begin
if fProcIsThreadSafe then
fProc
else
Synchronize(procedure begin fProc; end);
end;
end.
Want the latest updates on software, tech news, and AI?
Get latest updates about software, tech news, and AI from SourceForge directly in your inbox once a month.