roast_soul
roast_soul

Reputation: 3650

Page_Load is finished, keep the thread alive?

I do a test in Page_Load function in asp.net

protected void Page_Load(object sender, EventArgs e) {

 Task.Factory.StartNew(() =>
    {
        while (true)
        {
            Response.Write("Hi");
            Thread.Sleep(100);
        }
    });

    Thread.Sleep(2000);
    Response.Write("hello");
}

I found the fact is that the task will be killed when the pageload function is finished.

Is that true? Or the task is still alive?

If I want the task is still alive, how can I do?

Upvotes: 1

Views: 138

Answers (1)

usr
usr

Reputation: 171206

Using the Response object on multiple threads is not safe. Also, after a request has ended using the Response is not going to be successful. Let's assume that you had properly locked it:

The task is not killed because ASP.NET does not even know that task exists. How could it? You never give a reference to that task to ASP.NET. Probably, you haven't really looked at the error message you get. That task probably had an exception.

Don't use ASP.NET objects in an unsafe way if you want that task to continue to run.

Upvotes: 0

Related Questions