I have a timer as
public static System.Timers.Timer timer_get = new System.Timers.Timer();
timer_get.Elapsed += new ElapsedEventHandler(Get_OnTimedEvent);
timer_get.Interval = 1000;
timer_get.Enabled = true;
It is hitting this method.
public static void GetListFromDb()
{
try
{
DataTable dt = new DataTable();
//..here is i am filling datatable
Parallel.ForEach(dt.AsEnumerable(), row => {
GetDataFromApi(row);
});
}
catch (Exception e)
{
//..
}
}
Each row has irrelevant webrequest
elements(url,type,etc). I am sending the webrequest method at the same time.
The problem is that that the webrequest
takes more time than the timer clock with 1000ms resolution above. Running requests are frequently hitting this problem and I don't know how to solve it. Is there any way to detect if a method is already running with a specific parameter?
If you can identify each request by some key, you can manage a dictionary for "running" requests
public static System.Timers.Timer timer_get = new System.Timers.Timer();
private static ConcurrentDictionary<string, bool> _runningRequests = new ConcurrentDictionary<string, bool>();
And then
static void GetDataFromApi(DataRow row)
{
var requestKey = (string)row["Url"];
if (_runningRequests.TryAdd(requestKey, true))
{
try
{
//send web request
}
finally
{
bool alreadyRunning;
_runningRequests.TryRemove(requestKey, out alreadyRunning);
}
}
}