blah blah blah is here! blah blah » Close

up1down
link

I have a little knowledge about thread but know nothing about using Timer in .NET
Can anyone give some tips about what it is, and when it's used?

last answered 2 years ago

1 answers

up0down
link

In the context of a web application, you can create background threads that run at timed intervals to mimic something like a scheduled task or windows service.

For example, say you need to run a background job that runs a particular routine (say to purge a table, etc), you can create a background thread to run every x minutes. One caveat to this approach is that when the asp.net recycles I believe the timer will be reset. This might not be a problem depending on how accurate you need your job to run at.

Here are some great resources to read up on:

1. simulating a windows service

2. background threads in asp.net

3. Another approach is to use a callback when a item in the cache is removed. This method basically will have your task run, but you can't really gaurantee it will run as expected as the asp.net can recycle the cache whenever it deems appropriate etc.

<html>

<Script runat=server language="C#">
static bool itemRemoved = false;
static CacheItemRemovedReason reason;
CacheItemRemovedCallback onRemove = null;

public void RemovedCallback(String k, Object v, CacheItemRemovedReason r){
itemRemoved = true;
reason = r;
}

public void AddItemToCache(Object sender, EventArgs e) {
itemRemoved = false;

onRemove = new CacheItemRemovedCallback(this.RemovedCallback);

if (Cache["Key1"] == null)
Cache.Add("Key1", "Value 1", null, DateTime.Now.AddSeconds(60), Cache.NoSlidingExpiration, CacheItemPriority.High, onRemove);
}

public void RemoveItemFromCache(Object sender, EventArgs e) {
if(Cache["Key1"] != null)
Cache.Remove("Key1");
}
</Script>
<body>
<Form runat="server">
<input type=submit OnServerClick="AddItemToCache" value="Add Item To Cache" runat="server"/>
<input type=submit OnServerClick="RemoveItemFromCache" value="Remove Item From Cache" runat="server"/>
</Form>
<% if (itemRemoved) {
Response.Write("RemovedCallback event raised.");
Response.Write("<BR>");
Response.Write("Reason: <B>" + reason.ToString() + "</B>");
}
else {
Response.Write("Value of cache key: <B>" + Server.HtmlEncode(Cache["Key1"] as string) + "</B>");
}
%>
</body>
</html>



reference: MSDN - CacheItemRemovedCallback

Thanks Elliot, though I'm still at the start position of ASP.NET I hope, the links and your code'll help me a lot later.

Feedback