简体   繁体   中英

ASP.NET Asynchronous web page with long processing thread

I have a page which performs a long processing (write some pdf somewhere) so I have the following:

My ArchiveDoc.aspx page : (the page has a Label (called progress) and Async="true" in page directive)

delegate void archiveFuncDelegate(int idTurnover, string serverMapPath);
delegate void UpdateUIDelegate(string Text);

protected void Page_Load(object sender, EventArgs e)
{
    Page.AddOnPreRenderCompleteAsync(BeginTask, EndTask);
    this.progress.Text = "0";
}

private void UpdateUI(string Text)
{
    this.progress.Text = Text;
}

private IAsyncResult BeginTask(object sender, EventArgs e, AsyncCallback cb, object state)
{

    // invoke
    archiveFuncDelegate del = asyncArchivageFacture;
    IAsyncResult result = del.BeginInvoke(cb,null); 
    return result;
}

private void EndTask(IAsyncResult ar)
{
    if (!ar.IsCompleted)
    {
        progress.Text = "Error";
    }
    else
    {
        progress.Text = "OK";
    }
}

#region Archive (thread)

// long processing task (exemple)
public void asyncArchivageFacture()
{
    // exemple
    int total = 101;
    int progress = 0;

    for(int i=0; i<total; i++)
    {
        progress = i*100 / total;
        updateUi.Invoke(progress + "%");
        Thread.Sleep(2000);
     }

}

#endregion

When I call my page, the thread is called (asyncArchivageFacture() as well as the UpdateUI()) but the web page never gets updated : I got the loading symbol in the browser with a blank page, and once the thread is completed, the page finally display 'OK'. It doesn't display the progress (10%.. 20%..)

Any idea what's wrong? Thanks!

This is because the response(html) is sent to the client only after the EndTask method is called. Whatever changes you are making to the progress.Text is on the server side where you are changing only a server side variable.

I ended up using a simple

Thread t = new Thread(..)

without delaring the page async=true.

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