Our threading example illustrated using a delegate of type ThreadStart. We pass such a delegate to the constructor of the Thread class. When we call the Start method of the thread, the callback function that is wrapped by the delegate will be called.
A powerful feature of delegates is that you can combine them. Delegates can be multicast, in which they have an invocation list of methods. When such a delegate is called, all the methods on the invocation list will be called in turn. The Delegate.Combine method can be used to combine the invocation methods of two delegate objects, and Delegate.Remove can be used to remove methods.[4]
[4] In C# you can use the overloaded + and – operators to combine and remove delegate methods. In PerlNET you must use the Combine and Remove methods.
As a simple illustration of combining delegates, consider the solution in the folder DelegateDemo. Like the previous example, there is a C# class library project ConsoleLog and a PerlNET-managed EXE project ThreadDemo. We have changed the PerlNET project to illustrate combining delegates.
#
# DialogDemo.pl
#
use strict;
use namespace "System";
use namespace "System.Threading";
use PerlNET qw(AUTOCALL);
my $slowLog = ConsoleLog->new(1000,5);
my $dlgSlow = ThreadStart->new($slowLog, "ConsoleThread");
my $dlgQuick = ThreadStart->new($slowLog, "QuickMethod");
my $dlgCombo = Delegate->Combine($dlgSlow, $dlgQuick);
my $slowThread = Thread->new($dlgCombo);
Console->WriteLine("Starting thread ...");
$slowThread->Start();
Console->WriteLine("Thread has started");
Now there is only one thread, but we create a combined delegate $dlgQuick with an invocation list of two methods that will get called when the thread starts up. Here is the output from running the program.
Starting thread ... Thread has started Thread 1: ticks = 0 Thread 1: ticks = 1000 Thread 1: ticks = 2000 Thread 1: ticks = 3000 Thread 1: ticks = 4000 Thread 1 is terminating QuickMethod called
Notice that the first method runs through to completion before the second method gets called.
18.117.216.229