开发者

How to use threading to call a repetitive process in .NET?

开发者 https://www.devze.com 2023-02-06 17:12 出处:网络
In my website, I need to do a repetitive task which should not affect the main activity and performance of the website.

In my website, I need to do a repetitive task which should not affect the main activity and performance of the website.

So I think I need to use threading. I am new into threading in .Net. How to use thr开发者_JAVA百科eading is .NET?

Any tutorials or reference to any article would be a great help.


Here is a great tutorial on how to do multi-threaded applications in .NET a simple way to get work done on another thread is to use a BackgroundWorker.

When working with heavy tasks on other threads over the web, you might want to initiate the request using Ajax and then "poll" for answers.

There's an article over at MSDN: Use Threads and Build Asynchronous Handlers in Your Server-Side Web Code, it's a bit old but I think you can get a basic understanding by reading it.


The proper way of doing this in an ASP.NET application is using HostingEnvironment.QueueBackgroundWorkItem. This ensures that the background task will shutdown gracefully when the IIS application is recycled, machine shut down or something like that.

Call this once somewhere in startup of the application:

HostingEnvironment.QueueBackgroundWorkItem(RunInBackground);

And then implement a method like this:

private async Task RunInBackground(CancellationToken cancellationToken)
{
    while (!cancellationToken.IsCancellationRequested)
    {
        // Repetetive task

        await Task.Delay(TimeSpan.FromMinutes(1));
    }
}

You could also use HostingEnvironment.RegisterObject and do things more manually. You would gain some control, but will be less simple.


There are different ways to make use of multithreading in .NET. As already mentionned, you can use a BackgroundWorker, but you can also make use of Task based Asynchronous Programming, which is the recommended way since the TPL is available in .NET

This means that you can offload work that needs to be done on another thread as simple as

Task.Factory.StartNew(() => DoSomeWork());

This article from Stephen Cleary is also an interesting read. It compares BackGroundWorker with TPL.

Also, keep in mind that if you execute long-running tasks in asp.net, your requests may take a long time to complete. It might be better to execute long-running tasks in another service, like Hangfire for example.

0

精彩评论

暂无评论...
验证码 换一张
取 消