简体   繁体   中英

Threading in asp.net crashing server

Hey guys, I'm trying to get threading to work in ASP.NET but for some reason it keeps crashing my local server, and simply does not work at all when uploaded online. Here's the code:

protected void testThread()
{
    for (int i = 0; i < 10; i++)
    {
        Response.Write("Threading! <br/><br/>");
        Thread.Sleep(500);
    }
}

protected void Button1_Click(object sender, EventArgs e)
{

    Thread oThread = new Thread(testThread);
    oThread.Priority = ThreadPriority.Lowest; //Tried with and without this

    // Start the thread
    oThread.Start();
}

Any ideas?

The HTTP Response has been already (very likely) sent by the time the thread hits it again. Threading does not work well with the ASP.NET page life cycle. Consider changing your process.

See this page for the challenges.

http://www.beansoftware.com/ASP.NET-Tutorials/Multithreading-Thread-Pool.aspx

protected void Button1_Click(object sender, EventArgs e)
{

    Thread oThread = new Thread(testThread);
    oThread.Priority = ThreadPriority.Lowest; //Tried with and without this

    // Start the thread
    oThread.Start();

    oThread.Join() 
    // defeats the purpose of multithreading, but you can't 
    // let the main thread return if the newly spawned thread 
    // it trying to use Response object.
}

Like what @Daniel said, Response may already have terminated by the time your thread runs. The solution is to keep the connection alive while the thread runs. We can do that by assigning and asynchronous task to do the job.

protected void Page_Load(object sender, EventArgs e)
{
    AddOnPreRenderCompleteAsync(new BeginEventHandler(Thread_BeginEvent), new EndEventHandler(Thread_EndEvent));
}
protected override void OnPreRender(EventArgs e)
{
    base.OnPreRender(e);
    Response.Write(result);
}

private string result;

IAsyncResult Thread_BeginEvent(object sender, EventArgs e, AsyncCallback cb, object extraData)
{
    WaitCallback w = new WaitCallback(Thread_DoWork);
    return w.BeginInvoke(sender, cb, extraData, w);
}
void Thread_EndEvent(IAsyncResult ar)
{
    WaitCallback w = ar.AsyncState as WaitCallback;
    if(w != null)
        w.EndInvoke(ar);
}

void Thread_DoWork(object state)
{
    result = "";
    for (int i = 0; i < 10; i++)
    {
        result += "Threading! <br/><br/>";
        Thread.Sleep(500);
    }
}

You might want to try this as well, though I'm not sure whether it works or not, but I suspect it will:

void Thread_DoWork(object state)
{
    for (int i = 0; i < 10; i++)
    {
        Response.Write("Threading! <br/><br/>");
        Thread.Sleep(500);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM