Threading in Delphi for .NET - Creating Threads Using Static Methods
(Page 5 of 15 )
Listing 14.3 Creating Threads Using Static Methods
1: program staticthreads;
2: {$APPTYPE CONSOLE}
3: uses
4: System.Threading;
5:
6: type
7: D4DNStaticThread = class
8: public
9: class procedure ThreadMePlease; static;
10: end;
11:
12: class procedure D4DNStaticThread.ThreadMePlease;
13: var
14: stop : integer;
15: curNum : integer;
16: rnd : System.Random;
17: begin
18: rnd := System.Random.Create;
19: curNum := rnd.Next(1000);
20: stop := curNum + 10;
21: while curNum < stop do
22: begin
23: writeln('Thread ', System.Threading.Thread.CurrentThread.Name,
24: 'current value is ', curNum);
25: inc(curNum);
26: // Randomly give up time-slice to other thread
27: if rnd.Next(100) < 50 then
28: Thread.Sleep(0);
29: end;
30: end;
31:
32: var
33: thrd1 : Thread;
34: thrd2 : Thread;
35: begin
36: Console.Writeline('Starting static method threading example...');
37:
38: // create the thread passing the static method
39: thrd1 := Thread.Create(@D4DNStaticThread.ThreadMePlease);
40: thrd1.Name := 'one';
41:
42: // create another identical thread
43: thrd2 := Thread.create(@D4DNStaticThread.ThreadMePlease);
44: thrd2.Name := 'two';
45:
46: // start both threads
47: thrd1.Start;
48: thrd2.Start;
49:
50: // wait until both threads have finished
51: thrd1.Join;
52: thrd2.Join;
53:
54: Console.Writeline('Done');
55: readln;
56: end.
Note: Find the code on the CD: \Code\Chapter 14\Ex02\.
In Listing 14.3, a thread is created on a static class method. Similar to threading instance methods, any static class method without parameters can be executed on a thread.
Listings 14.2 and 14.3 contain a subtle bug. The output written to the console is performed in an unsynchronized manner. It is very likely that the output between two threads will be mixed together. This is caused by the implementation of the writeln procedure by the Delphi compiler and the runtime library. Each parameter passed to the writeln procedure results in a separate call to either the Console.Write or Console.WriteLine method. Changing the writeln (on line 31 in Listing 14.2, and line 23 in Listing 14.3) to use Console.WriteLine instead or passing only one parameter to the writeln procedure (for example, using writeln(Format(..));) will produce the proper behavior.
This chapter is from Delphi for .NET Developer's Guide, by Xavier Pacheco (Sams, 2004, ISBN: 0-672-32443-1). Check it out at your favorite bookstore today.
Buy this book now. |
Next: Threading Priority >>
More .NET Articles
More By Xavier Pacheco