Reputation: 25
I am using System.Threading.Timer
to create a timer that prints a string to a serial port and then reads from another serial port every second. I am trying to do this by sending arguments to my TimerCallback
function. Below is my code where the timer is initialized and the code for the callback function.
Initialization:
TimerCallback tcb = Timer_func(buff_out, send_port, recv_port);
AutoResetEvent autoEvent = new AutoResetEvent(false);
Timer aTimer = new Timer(tcb,autoEvent,1000,1000);
Callback function:
public static TimerCallback Timer_func(string buff_out, SerialPort send_port, SerialPort recv_port)
{
string buff_in;
send_port.WriteLine(buff_out);
buff_in = recv_port.ReadLine();
Console.WriteLine(buff_in);
}
The initialization occurs in the Main() function, and both functions are in the same class.
When I compile the code as is I recieve error CS0161: "not all code paths return a value". In attempts to remedy this I've added return 1;
to the end of that function but then I recieve error CS0029: "cannot explicitly convert type 'int' to 'System.Threading.Timer'.
What am I doing wrong, and how can I fix it. (New to C#). Thank you in advance!
Upvotes: 1
Views: 1680
Reputation: 887479
You're misunderstanding delegates.
TimerCallback
is a delegate type – a type that can hold a function.
TimerCallback
can only hold functions with the signature
void MethodName(Object state)
When you write
public static TimerCallback Timer_func(...) { ... }
You just declared a function that returns a TimerCallback
delegate.
Thus, your function must return a function that matches TimerCallback.
You can do that using an anonymous delegate:
return delegate (object state) {
string buff_in;
send_port.WriteLine(buff_out);
buff_in = recv_port.ReadLine();
Console.WriteLine(buff_in);
};
Upvotes: 5