I am calling a C# class dll in my C# service app. But in the class dll, at some point there has to be executed a method that is defined on the caller app. So I want to pass, like a parameter, a whole method to the dll, that has to be executed at a specific time.
The challainging point is that the function has to be executed in the dll, in a timer event. How can I pass my function in this case?
My C# app where I call the dll.
using MyClassLibrary; // my dll
namespace Concheetah_Service_Bahmuller
{
public partial class Service1 : ServiceBase
{
public Service1()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
MyClassLibrary.Main_Prog main_Prog = new MyClassLibrary.Main_Prog();
main_Prog.Main_Start(); // starting point of my dll
}
public void func_passed()
{
// some supplementary code
}
}
}
MyClassLibrary
System.Timers.Timer timer1 = new System.Timers.Timer();
public void Main_Start()
{
Initialize_timer1(); // starting point of the dll
}
public void Initialize_timer1()
{
timer1.Elapsed += new ElapsedEventHandler(OnTimedEvent_timer1);
timer1 = 35;
timer1.Start();
}
private void OnTimedEvent_timer1(object sender, EventArgs e)
{
//some code
func_passed(); // at this point my passed function should be executed.
}
Have a look at Delegates, Anonymous Methods and Lambda Expressions.
Note that it makes no difference whether the code is in another DLL (in another assembly in C# terms) or not as long as you have a reference to this other project or assembly and the things you want to access are public.
Change the library like this (showing only changed things):
private Action _timerAction;
public void Main_Start(Action timerAction)
{
_timerAction = timerAction;
Initialize_timer1();
}
private void OnTimedEvent_timer1(object sender, EventArgs e)
{
//some code
_timerAction();
// If _timerAction can be null, call it like this instead:
_timerAction?.Invoke();
}
Then call it like this from the application:
main_Prog.Main_Start(func_passed);
Make sure not to add braces ()
after func_passed
since we don't want to call the function here, we want to pass the function itself as an argument.
There are different Action and Func Delegates having a different number of parameters. Unlike Action
, Func
has a return type other than void
.
Another way to solve the problem is to have the library expose an event the application can subscribe to.
See also: Handle and raise events