Friday, December 19, 2003 5:00 PM
richard
Delegate Adapter: map any method to a ThreadStart, WaitCallback or TimerCallback
I posted a new sample (hopefully interesting) to GotDotNet.com user samples. It's a class that allows you to map any delegate (and therefore any method) to the ThreadStart, WaitCallback or TimerCallback delegates. I got the idea from seeing a bunch of posts in the microsoft.public.dotnet.languages.csharp newsgroup asking how to start a new Thread while passing in arguments to the method the Thread was running. The 'normal' way to do it is to create an object that holds the data you would pass in arguments and then refactor or wrap your method on this class to match the ThreadStart delegate's signature (no parameters, void return). This class demonstrates how to call any method (which you may not have the source for anyway) using a ThreadStart, WaitCallback or TimerCallback delegate.
Here is the sample calling code showing how easy it makes it to call a method of any signature (at least I think it's easy!)
using System;
using System.Collections;
using System.Threading;
using Timing;
using DelegateAdapter;
public class Program
{
public delegate double WorkMethodHandler(double factor, string name);
public static double WorkMethod(double factor, string name)
{
Console.WriteLine(name);
return 3.14159 * factor;
}
public static void Main()
{
DelegateAdapter adapter = new DelegateAdapter(new WorkMethodHandler(WorkMethod), 3.123456789, "Richard");
Thread worker = new Thread(adapter);
adapter.Args = new object[] {9.14159d, "Roberto"};
worker.Start();
worker.Join();
Console.WriteLine(adapter.ReturnValue);
}
}