Reputation: 417
I have timed code that checks for dead peers. I use System.Threading.Timer to do that. The detection code works and I call it like this :
Timer SocketKPATimer = new Timer(delegate { timedcode(state); }, null, 5000, 5000);
where state is a StateObject that's used to
Socket handler = state.workSocket;
and later ...
handler.Shutdown(SocketShutdown.Both);
//I need to stop the Timer here
The method itself is defined as
static void timedcode(StateObject state) {...}
now the problem is that after I detect that something went wrong with the peer I need the SocketKPATimer to stop and I can't. How do I need to modify timedcode so I can stop the timer please?
Upvotes: 2
Views: 196
Reputation: 1092
One way you are going to get access to the SocketKPATimer
is to pass the Timer
into the timedcode(state)
method in the state object. That means you will have to create a class that contains properties for the Socket
and a Timer
. Then you can define the Timer
first and then instantiate it with a delegate and reference the Timer
. This does not handle any sort of concurrency issues with accessing the 'Timer'. You should be using typical multi-threading techniques for that.
Example:
class State
{
public Socket WorkSocket { get; set; }
public System.Threading.Timer TimerThingy { get; set; }
}
private void Nothing()
{
Socket someSocket = null;
System.Threading.Timer socketKPATimer = null;
State state = new State();
state.WorkSocket = someSocket;
state.TimerThingy = socketKPATimer;
socketKPATimer = new System.Threading.Timer(delegate { timedcode(state); }, null, 5000, 5000);
}
private void timedcode(object state)
{
var s = state as State;
Socket hander = s.WorkSocket;
System.Threading.Timer timer = s.TimerThingy;
hander.Shutdown(SocketShutdown.Both);
}
Upvotes: 1