How to add a new thread for executing particular function in ASP.NET website?
In my website, I want to create a separate thread for a process which needs to constantly run in the background. I want to use threading so that my website performance is not degraded.
I want to create thread for following code.
[WebMethod]
public void iterativeFunction()
{
int count = 0;
DateTime date1 = new DateTime(2011,5,31);
while (System.DateTime.Compare(System.DateTime.Now,date1)<0)
{
downloadAndParse();
count++;
}
}
How should I add a n开发者_如何学JAVAew thread for this function?
Something like this:
public static class BackgroundHelper
{
private static readonly object _syncRoot = new object();
private static readonly ManualResetEvent _event = new ManualResetEvent(false);
private static Thread _thread;
public static bool Running { get; private set; }
public static void Start()
{
lock (_syncRoot)
{
if (Running)
return;
Running = true;
// Reset the event so we can use it to stop the thread.
_event.Reset();
// Star the background thread.
_thread = new Thread(new ThreadStart(BackgroundProcess));
_thread.Start();
}
}
public static void Stop()
{
lock (_syncRoot)
{
if (!Running)
return;
Running = false;
// Signal the thread to stop.
_event.Set();
// Wait for the thread to have stopped.
_thread.Join();
_thread = null;
}
}
private static void BackgroundProcess()
{
int count = 0;
DateTime date1 = new DateTime(2011, 5, 31);
while (System.DateTime.Compare(System.DateTime.Now, date1) < 0)
{
downloadAndParse();
// Wait for the event to be set with a maximum of the timeout. The
// timeout is used to pace the calls to downloadAndParse so that
// it not goes to 100% when there is nothing to download and parse.
bool result = _event.WaitOne(TimeSpan.FromMinutes(1));
// If the event was set, we're done processing.
if (result)
break;
count++;
}
}
private static void downloadAndParse()
{
// Your download and parse logic here.
}
}
Then in your web service:
[WebMethod]
public void iterativeFunction()
{
BackgroundHelper.Start();
}
精彩评论