Reputation: 1615
I have a C# class with an array of objects, each object representing an open connection to an external device. The connections time out by default after n idle hours which I want to avoid. I plan to make use of a timer that trips every n-2 idle hours, with a callback that invokes a method to touch each object and effectively reset the timeout.
The class needs to be usable in both Windows forms and non forms-based projects, hence I am considering using System.Timers.Timer and a lock to restrict any other thread from accessing the array during timeout reset.
Using a timer introduces thread safety implications, e.g. if one of the objects is destructed in between the timer callback determining that an object exists and resetting its timeout, there will be an attempt to read uninitialised memory. However, my problem is that the array is accessed in a number of places in the class. The lock should prevent all access to the array while the timer callback is in progress as follows:
class MyClass
{
private System.Timers.Timer timer;
private object locker = new object();
public void Run()
{
timer = new System.Timers.Timer();
timer.Interval = 21600000; //6 hours
timer.Elapsed += AccessArrayCallback;
timer.Start();
}
public void AccessArrayCallback(object sender, EventArgs e)
{
timer.Enabled = false;
lock (locker)
{
/*
if (called by timer)
{
iterate through array and reset connections;
}
else
{
Call appropriate function that reads/writes array using EventArgs delegate
}
*/
}
timer.Enabled = true;
}
}
A few questions before I continue with this approach:
Is there an established pattern/more elegant approach to this kind of problem?
Is it correct to use a delegate in EventArgs? Any other method in the class requiring access to the array will call the callback and populate EventArgs appropriately.
Thanks in advance.
Upvotes: 2
Views: 4133
Reputation:
Since the lock is a private object, the other part of the system won't be able to access it to acheive your desired level of thread saftey. This is why Concurrent Bag and it's friends were created. The delegate part if fine though.
Upvotes: 3