0

When a thread is created as a task on projects written in asp.net webform or .Net Core Web and is added to a server, it stops running after a while without a reason or exception.

Task.Factory.StartNew(async () =>
{
    //...
}, _cancellationToken, TaskCreationOptions.LongRunning, TaskScheduler.Current);

I need to use a task as endless scheduling; how can I do it on projects written in asp.net webform or .Net Core Web?

The problem is only for web projects, for example in console projects it works properly.

iman kari
  • 93
  • 1
  • 6
  • 1
    Does this answer your question? [Proper way to implement a never ending task. (Timers vs Task)](https://stackoverflow.com/questions/13695499/proper-way-to-implement-a-never-ending-task-timers-vs-task) – Sinatr Apr 13 '21 at 10:27
  • *"it stops running after a while without a reason"* - you have to provide more info, ideally [mcve]. – Sinatr Apr 13 '21 at 10:28
  • does the task have a try-catch block? might it be that a non-catchable exception is being thrown (like invalidAccessException)? – Amo Robb Apr 13 '21 at 10:39
  • 1
    There are a *lot* of duplicates for this. You can't just start a task and expect it to run forever. All web servers kill/reset the objects used to server a request. The web servers can recycle applications and sites, either on a schedule or when there's suspicious behavior, like a runaway process that's eating up all CPU or RAM. That's why you *must* use at least a hosted service – Panagiotis Kanavos Apr 13 '21 at 11:33

1 Answers1

2

You shouldn't use tasks to launch fire-and-forget jobs, since there is nobody to cache exceptions from it. You also won't be able to use scoped services from there (like the DB), since it'll mess the scope management. To get the background-running process you can use HostedService

public class MyHostedService : BackgroundService
{
    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        // this starts on app startup in a separate thread
        while (!stoppingToken.IsCancellationRequested)
        {
            // do your stuff
        }
    }
}

// in Startup.ConfigureServices
services.AddHostedService<MyHostedService>();

As a simpler solution you can use a third-party nuget, like Hangfire, which deals with all the technical boilerplate, and lets you to just start the fire-and-forget jobs right away hangfireClient.Enqueue(() => { ... }). It also allows to setup cron-type scheduled jobs, and lots of other stuff.

Morse
  • 1,330
  • 2
  • 17
  • 27
  • Thank you, What is the solution for older versions? for example asp.net webform? – iman kari Apr 13 '21 at 12:23
  • 1
    Sorry, never worked with .net, only with .net-core. For core it's available since 2.1, AFAIK. So it's quite old. – Morse Apr 13 '21 at 12:26