Dynamically load and call delegates based on source data
Posted
by
makerofthings7
on Programmers
See other posts from Programmers
or by makerofthings7
Published on 2012-05-10T12:30:35Z
Indexed on
2012/10/17
11:21 UTC
Read the original article
Hit count: 250
c#
|dynamic-typing
Assume I have a stream of records that need to have some computation. Records will have a combination of these functions run Sum
, Aggregate
, Sum over the last 90 seconds
, or ignore
.
A data record looks like this:
Date;Data;ID
Question
Assuming that ID is an int
of some kind, and that int corresponds to a matrix of some delegates to run, how should I use C# to dynamically build that launch map?
I'm sure this idea exists... it is used in Windows Forms which has many delegates/events, most of which will never actually be invoked in a real application.
The sample below includes a few delegates I want to run (sum, count, and print) but I don't know how to make the quantity of delegates fire based on the source data. (say print the evens, and sum the odds in this sample)
using System;
using System.Threading;
using System.Collections.Generic;
internal static class TestThreadpool
{
delegate int TestDelegate(int parameter);
private static void Main()
{
try
{
// this approach works is void is returned.
//ThreadPool.QueueUserWorkItem(new WaitCallback(PrintOut), "Hello");
int c = 0;
int w = 0;
ThreadPool.GetMaxThreads(out w, out c);
bool rrr =ThreadPool.SetMinThreads(w, c);
Console.WriteLine(rrr);
// perhaps the above needs time to set up6
Thread.Sleep(1000);
DateTime ttt = DateTime.UtcNow;
TestDelegate d = new TestDelegate(PrintOut);
List<IAsyncResult> arDict = new List<IAsyncResult>();
int count = 1000000;
for (int i = 0; i < count; i++)
{
IAsyncResult ar = d.BeginInvoke(i, new AsyncCallback(Callback), d);
arDict.Add(ar);
}
for (int i = 0; i < count; i++)
{
int result = d.EndInvoke(arDict[i]);
}
// Give the callback time to execute - otherwise the app
// may terminate before it is called
//Thread.Sleep(1000);
var res = DateTime.UtcNow - ttt;
Console.WriteLine("Main program done----- Total time --> " + res.TotalMilliseconds);
}
catch (Exception e)
{
Console.WriteLine(e);
}
Console.ReadKey(true);
}
static int PrintOut(int parameter)
{
// Console.WriteLine(Thread.CurrentThread.ManagedThreadId + " Delegate PRINTOUT waited and printed this:"+parameter);
var tmp = parameter * parameter;
return tmp;
}
static int Sum(int parameter)
{
Thread.Sleep(5000); // Pretend to do some math... maybe save a summary to disk on a separate thread
return parameter;
}
static int Count(int parameter)
{
Thread.Sleep(5000); // Pretend to do some math... maybe save a summary to disk on a separate thread
return parameter;
}
static void Callback(IAsyncResult ar)
{
TestDelegate d = (TestDelegate)ar.AsyncState;
//Console.WriteLine("Callback is delayed and returned") ;//d.EndInvoke(ar));
}
}
© Programmers or respective owner