in my csharp application i have certain events which should trigger functions to be called on a specific thread, which is looping through some code.
now, instead of storing all this data by hand and having a big switch-case i was wondering if it is possible to store these functions and their paramteres in a list which is then processed by the other thread?
pseudo code:
var func = pointer2somefunction(13, "abc");
list.add(func);
other thread:
while (list.Count > 0)
{
var func = list.Remove(0);
func.Invoke();
}
Yes, you can do this by using a List<Action>
or a Queue<Action>
which suits slightly better in my opinion. Action
is a type for a no-parameter void delegate:
var functions = new Queue<Action>();
functions.Enqueue(() => Console.WriteLine("Foo"));
functions.Enqueue(() => Console.WriteLine("Bar"));
while (functions.Any())
{
// note the double parenthesis here: one for Dequeue
// and one for your dequeued function
functions.Dequeue()();
}
If you need parameters, use Action<T>
for one, Action<T, T>
for two and so forth. For a return value, use Func
instead of Action
(or Func<T>
etc.).
Maybe an event would help you too. Events are C#'s language feature to use the observer pattern.
// events are usually on the instance rather than static
private static event EventHandler MyEvent;
static void Main(string[] args)
{
MyEvent += (s, e) => Console.WriteLine("FooEvent");
MyEvent += (s, e) => Console.WriteLine("BarEvent");
MyEvent(null, EventArgs.Empty);
}
An event is a multicast delegate, which is a delegate to a list of functions. You cannot control the threading for each handler though: Unlike the Queue<Action>
above, where you can start or reuse threads, a multicast delegate is exposed as one call from outside, letting you use only one thread for all invocations.
I think you are implementing events in that way. You don't need a big switch case, you need several events, and then trigger the right event in the right time, and register it with the right method.
You can do a list of delegates, but it'll start getting complicated when you want different function with different set of parameters.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With