PageAsyncTask Classe

Definizione

Contiene informazioni su un'attività asincrona registrata in una pagina. La classe non può essere ereditata.

public ref class PageAsyncTask sealed
public sealed class PageAsyncTask
type PageAsyncTask = class
Public NotInheritable Class PageAsyncTask
Ereditarietà
PageAsyncTask

Esempio

Nell'esempio di codice seguente vengono registrate tre attività asincrone in una pagina ed eseguite in parallelo. Ogni attività chiama un metodo che limita la sospensione del thread per 5 secondi.

<%@ Page Language="C#" Async="true" AsyncTimeout="35"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
    
  protected void Page_Load(object sender, EventArgs e)
  {
      
    // Define the asynchronuous task.
    Samples.AspNet.CS.Controls.SlowTask slowTask1 =    
      new Samples.AspNet.CS.Controls.SlowTask();
    Samples.AspNet.CS.Controls.SlowTask slowTask2 =
    new Samples.AspNet.CS.Controls.SlowTask();
    Samples.AspNet.CS.Controls.SlowTask slowTask3 =
    new Samples.AspNet.CS.Controls.SlowTask();
    
    // <Snippet3> 
    PageAsyncTask asyncTask1 = new PageAsyncTask(slowTask1.OnBegin, slowTask1.OnEnd, slowTask1.OnTimeout, "Async1", true);
    PageAsyncTask asyncTask2 = new PageAsyncTask(slowTask2.OnBegin, slowTask2.OnEnd, slowTask2.OnTimeout, "Async2", true);
    PageAsyncTask asyncTask3 = new PageAsyncTask(slowTask3.OnBegin, slowTask3.OnEnd, slowTask3.OnTimeout, "Async3", true);

    // Register the asynchronous task.
    Page.RegisterAsyncTask(asyncTask1);
    Page.RegisterAsyncTask(asyncTask2);
    Page.RegisterAsyncTask(asyncTask3);
    // </Snippet3>
      
    // Execute the register asynchronous task.
    Page.ExecuteRegisteredAsyncTasks();

    TaskMessage.InnerHtml = slowTask1.GetAsyncTaskProgress()+ "<br />" + slowTask2.GetAsyncTaskProgress() + "<br />" + slowTask3.GetAsyncTaskProgress();

  }
</script>

<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
    <title>Asynchronous Task Example</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
      <span id="TaskMessage" runat="server">
      </span>
    </div>
    </form>
</body>
</html>
<%@ Page Language="VB" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
      
        ' Define the asynchronuous task.
        Dim slowTask1 As New Samples.AspNet.VB.Controls.SlowTask()
        Dim slowTask2 As New Samples.AspNet.VB.Controls.SlowTask()
        Dim slowTask3 As New Samples.AspNet.VB.Controls.SlowTask()
     
        ' <Snippet3>
        Dim asyncTask1 As New PageAsyncTask(AddressOf slowTask1.OnBegin, AddressOf slowTask1.OnEnd, AddressOf slowTask1.OnTimeout, "Async1", True)
        Dim asyncTask2 As New PageAsyncTask(AddressOf slowTask2.OnBegin, AddressOf slowTask2.OnEnd, AddressOf slowTask2.OnTimeout, "Async2", True)
        Dim asyncTask3 As New PageAsyncTask(AddressOf slowTask3.OnBegin, AddressOf slowTask3.OnEnd, AddressOf slowTask3.OnTimeout, "Async3", True)

        ' Register the asynchronous task.
        Page.RegisterAsyncTask(asyncTask1)
        Page.RegisterAsyncTask(asyncTask2)
        Page.RegisterAsyncTask(asyncTask3)
        ' </Snippet3>
      
        ' Execute the register asynchronous task.
        Page.ExecuteRegisteredAsyncTasks()

        TaskMessage.InnerHtml = slowTask1.GetAsyncTaskProgress() + "<br />" + slowTask2.GetAsyncTaskProgress() + "<br />" + slowTask3.GetAsyncTaskProgress()

    End Sub
</script>

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <span id="TaskMessage" runat="server">
      </span>
    </div>
    </form>
</body>
</html>
using System;
using System.Web;
using System.Web.UI;
using System.Threading;

namespace Samples.AspNet.CS.Controls
{
    public class SlowTask
    {
        private String _taskprogress;
        private AsyncTaskDelegate _dlgt;

        // Create delegate.
        protected delegate void AsyncTaskDelegate();

        public String GetAsyncTaskProgress()
        {
            return _taskprogress;
        }
        public void ExecuteAsyncTask()
        {
            // Introduce an artificial delay to simulate a delayed 
            // asynchronous task.
            Thread.Sleep(TimeSpan.FromSeconds(5.0));
        }

        // Define the method that will get called to
        // start the asynchronous task.
        public IAsyncResult OnBegin(object sender, EventArgs e,
            AsyncCallback cb, object extraData)
        {
            _taskprogress = "AsyncTask started at: " + DateTime.Now + ". ";

            _dlgt = new AsyncTaskDelegate(ExecuteAsyncTask);
            IAsyncResult result = _dlgt.BeginInvoke(cb, extraData);

            return result;
        }

        // Define the method that will get called when
        // the asynchronous task is ended.
        public void OnEnd(IAsyncResult ar)
        {
            _taskprogress += "AsyncTask completed at: " + DateTime.Now;
            _dlgt.EndInvoke(ar);
        }

        // Define the method that will get called if the task
        // is not completed within the asynchronous timeout interval.
        public void OnTimeout(IAsyncResult ar)
        {
            _taskprogress += "AsyncTask failed to complete " +
                "because it exceeded the AsyncTimeout parameter.";
        }
    }
}
Imports System.Threading

Namespace Samples.AspNet.VB.Controls

    Public Class SlowTask
        Private _taskprogress As String
        Private _dlgt As AsyncTaskDelegate

        ' Create delegate.
        Protected Delegate Sub AsyncTaskDelegate()

        Public Function GetAsyncTaskProgress() As String
            Return _taskprogress
        End Function

        Public Sub ExecuteAsyncTask()
            ' Introduce an artificial delay to simulate a delayed 
            ' asynchronous task.
            Thread.Sleep(TimeSpan.FromSeconds(5.0))
        End Sub

        ' Define the method that will get called to
        ' start the asynchronous task.
        Public Function OnBegin(ByVal sender As Object, ByVal e As EventArgs, ByVal cb As AsyncCallback, ByVal extraData As Object) As IAsyncResult
            _taskprogress = "AsyncTask started at: " + DateTime.Now.ToString + ". "

            _dlgt = New AsyncTaskDelegate(AddressOf ExecuteAsyncTask)
            Dim result As IAsyncResult = _dlgt.BeginInvoke(cb, extraData)

            Return result
        End Function

        ' Define the method that will get called when
        ' the asynchronous task is ended.
        Public Sub OnEnd(ByVal ar As IAsyncResult)
            _taskprogress += "AsyncTask completed at: " + DateTime.Now.ToString
            _dlgt.EndInvoke(ar)
        End Sub


        ' Define the method that will get called if the task
        ' is not completed within the asynchronous timeout interval.
        Public Sub OnTimeout(ByVal ar As IAsyncResult)
            _taskprogress += "AsyncTask failed to complete " + _
                "because it exceeded the AsyncTimeout parameter."
        End Sub
    End Class
End Namespace

Commenti

ASP.NET versione 2.0 consente di registrare più attività in una pagina ed eseguirle in modo asincrono prima di eseguire il rendering della pagina. È possibile specificare che un'attività venga eseguita in modo asincrono se si tratta di un processo lento e non si vuole che altri processi vengano associati durante l'esecuzione. Le attività asincrone possono essere eseguite in parallelo o in sequenza.

Un PageAsyncTask oggetto deve essere registrato nella pagina tramite il RegisterAsyncTask metodo . La pagina stessa non deve essere elaborata in modo asincrono per eseguire attività asincrone. È possibile impostare l'attributo Async su true (come illustrato nell'esempio di codice seguente) o false nella direttiva page e le attività asincrone verranno comunque elaborate in modo asincrono:

<%@ Page Async="true" %>

Quando l'attributo Async è impostato su false, il thread che esegue la pagina verrà bloccato fino al completamento di tutte le attività asincrone.

Tutte le attività asincrone registrate prima dell'evento PreRenderComplete verranno eseguite automaticamente dalla pagina se non sono già state eseguite. Tali attività asincrone registrate dopo l'evento PreRenderComplete devono essere eseguite in modo esplicito tramite il ExecuteRegisteredAsyncTasks metodo . Il ExecuteRegisteredAsyncTasks metodo può essere usato anche per avviare le attività prima dell'evento PreRenderComplete . Il ExecuteRegisteredAsyncTasks metodo esegue tutte le attività asincrone registrate nella pagina che non sono state eseguite.

Per impostazione predefinita, un'attività asincrona raggiunge il timeout se non è stata completata entro 45 secondi. È possibile specificare un valore di timeout diverso nel file Web.config o nella direttiva page. La <pages> sezione del file Web.config contiene un asyncTimeout attributo, come illustrato di seguito.

<system.web>

<pages asyncTimeout="30">

</pages>

</system.web>

La direttiva page contiene un AsyncTimeout attributo .

<%@ Page AsyncTimeout="30" %>

Costruttori

Nome Descrizione
PageAsyncTask(BeginEventHandler, EndEventHandler, EndEventHandler, Object, Boolean)

Inizializza una nuova istanza della PageAsyncTask classe utilizzando il valore specificato per l'esecuzione in parallelo.

PageAsyncTask(BeginEventHandler, EndEventHandler, EndEventHandler, Object)

Inizializza una nuova istanza della PageAsyncTask classe utilizzando il valore predefinito per l'esecuzione in parallelo.

PageAsyncTask(Func<CancellationToken,Task>)

Inizializza una nuova istanza della PageAsyncTask classe utilizzando un gestore eventi che consente di annullare l'attività.

PageAsyncTask(Func<Task>)

Inizializza una nuova istanza della PageAsyncTask classe utilizzando un gestore eventi che consente di gestire l'attività.

Proprietà

Nome Descrizione
BeginHandler

Ottiene il metodo da chiamare all'inizio di un'attività asincrona.

EndHandler

Ottiene il metodo da chiamare quando l'attività viene completata correttamente entro il periodo di timeout.

ExecuteInParallel

Ottiene un valore che indica se l'attività può essere elaborata in parallelo con altre attività.

State

Ottiene un oggetto che rappresenta lo stato dell'attività.

TimeoutHandler

Ottiene il metodo da chiamare quando l'attività non viene completata correttamente entro il periodo di timeout.

Metodi

Nome Descrizione
Equals(Object)

Determina se l'oggetto specificato è uguale all'oggetto corrente.

(Ereditato da Object)
GetHashCode()

Funge da funzione hash predefinita.

(Ereditato da Object)
GetType()

Ottiene il Type dell'istanza corrente.

(Ereditato da Object)
MemberwiseClone()

Crea una copia superficiale del Objectcorrente.

(Ereditato da Object)
ToString()

Restituisce una stringa che rappresenta l'oggetto corrente.

(Ereditato da Object)

Si applica a