ammcom
ammcom

Reputation: 1034

Asp .Net background worker thread

I am planning to start a background thread in the application start event of an ASP .net website (inside global.asax).

I've read in many places that this is not a good practice, as this thread may crash the whole IIS process or may cause other problems.

I need to start a background thread that connects periodically to another server and update the database, so:

What is the best practice in this case? Can I just mark the thread as background so that it is stopped automatically when other threads stops? and if it is not a good choice to start a thread in this situation what is the best replacement?

Upvotes: 1

Views: 1311

Answers (2)

usr
usr

Reputation: 171178

Be aware that any background work in ASP.NET can go away without warning when the AppDomain recycles. Windows Services and Scheduled Tasks have less reasons to go away but they, too, can disappear (reboot, deployment, bluescreen, power loss, or god forbid a bug in your code!).

You must be able to tolerate any work disappearing. As long as that is the case you can start background work safely.

You can use a timer, or more simply a task that just does:

while (true) {
 DoWork();
 await Task.Delay(...);
}

Be sure to log errors.

Upvotes: 3

zavolokas
zavolokas

Reputation: 707

Consider using Azure. There you could make use of a WebJob or WorkerRole

Upvotes: 0

Related Questions