Expandir Minimizar
Este artículo proviene de un motor de traducción automática. Mueva el puntero sobre las frases del artículo para ver el texto original. Más información.
Traducción
Original
Este tema aún no ha recibido ninguna valoración - Valorar este tema

Page.ExecuteRegisteredAsyncTasks (Método)

Inicia la ejecución de una tarea asincrónica.

Espacio de nombres:  System.Web.UI
Ensamblado:  System.Web (en System.Web.dll)
public void ExecuteRegisteredAsyncTasks()
ExcepciónCondición
HttpException

Hay una excepción en la tarea asincrónica.

Defina una tarea asincrónica mediante la clase PageAsyncTask. Una vez definida la tarea, y después de registrarla con la página mediante el método RegisterAsyncTask, se puede invocar el método ExecuteRegisteredAsyncTasks para comenzar la tarea asincrónica.

La llamada al método ExecuteRegisteredAsyncTasks se produce automáticamente en la fase de procesamiento de la página en que se llama a las tareas asincrónicas registradas, si existen, para una página no asincrónica. Esta llamada automática a ExecuteRegisteredAsyncTasks se produce justo antes del evento PreRenderComplete. Llame al método ExecuteRegisteredAsyncTasks cuando desee invocar tareas en otras ocasiones. Tenga en cuenta que las tareas asincrónicas se ejecutarán una sola vez, mientras que puede llamar a ExecuteRegisteredAsyncTasks más de una vez.

La propiedad AsyncTimeout se restablece en cada llamada al método ExecuteRegisteredAsyncTasks. El último valor de AsyncTimeout anterior a la invocación del método ExecuteRegisteredAsyncTasks tiene prioridad. Si una tarea asincrónica toma más tiempo que el valor de AsyncTimeout, las tareas subsiguientes invocadas durante esa llamada a ExecuteRegisteredAsyncTasks agotan el tiempo de espera inmediatamente.

En el ejemplo de código siguiente se muestra cómo utilizar la propiedad AsyncTimeout con los métodos ExecuteRegisteredAsyncTasks y RegisterAsyncTask. Tenga en cuenta el uso de los controladores de inicio, finalización y tiempo de espera. En el ejemplo, se introduce un retraso artificial para ilustrar la situación en que una tarea asincrónica supera el tiempo asignado mediante la propiedad AsyncTimeout. En un escenario real, se podría utilizar una tarea asincrónica para realizar llamadas de base de datos o generar imágenes, por ejemplo, y el controlador de tiempo de espera aplicaría la degradación correcta si la tarea no se realizase en el tiempo indicado.


<%@ Page Language="VB" AsyncTimeout="2"%>

<!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 System.EventArgs)

    ' Define the asynchronuous task.
    Dim mytask As New Samples.AspNet.VB.Controls.MyAsyncTask()
    Dim asynctask As New PageAsyncTask(AddressOf mytask.OnBegin, AddressOf mytask.OnEnd, AddressOf mytask.OnTimeout, DBNull.Value)

    ' Register the asynchronous task.
    Page.RegisterAsyncTask(asynctask)

    ' Execute the register asynchronous task.
    Page.ExecuteRegisteredAsyncTasks()

    TaskMessage.InnerHtml = mytask.GetAsyncTaskProgress()

  End Sub
</script>

<html xmlns="http://www.w3.org/1999/xhtml" >
<head 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="C#" AsyncTimeout="2"%>

<!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.MyAsyncTask mytask =    
      new Samples.AspNet.CS.Controls.MyAsyncTask();
    PageAsyncTask asynctask = new PageAsyncTask(mytask.OnBegin, mytask.OnEnd, mytask.OnTimeout, null);

    // Register the asynchronous task.
    Page.RegisterAsyncTask(asynctask);

    // Execute the register asynchronous task.
    Page.ExecuteRegisteredAsyncTasks();

    TaskMessage.InnerHtml = mytask.GetAsyncTaskProgress();

  }
</script>

<html xmlns="http://www.w3.org/1999/xhtml" >
<head 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>



Imports Microsoft.VisualBasic
Imports System
Imports System.Web
Imports System.Web.UI
Imports System.Threading

Namespace Samples.AspNet.VB.Controls

    Public Class MyAsyncTask

        Private _taskprogress As String
        Private _dlgt As AsyncTaskDelegate

        ' Create delegate.
        Delegate Function AsyncTaskDelegate()

        Public Function GetAsyncTaskProgress() As String
            Return _taskprogress
        End Function

        Public Function DoTheAsyncTask()

            ' Introduce an artificial delay to simulate a delayed 
            ' asynchronous task. Make this greater than the 
            ' AsyncTimeout property.
            Thread.Sleep(TimeSpan.FromSeconds(5.0))

        End Function


        ' 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 = "Beginning async task."

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

        End Function 'OnBegin

        ' Define the method that will get called when
        ' the asynchronous task is ended.
        Public Sub OnEnd(ByVal ar As IAsyncResult)

            _taskprogress = "Asynchronous task completed."
            _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 = "Ansynchronous task failed to complete because " & _
            "it exceeded the AsyncTimeout parameter."

        End Sub

    End Class

End Namespace




using System;
using System.Web;
using System.Web.UI;
using System.Threading;

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

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

		public String GetAsyncTaskProgress()
		{
			return _taskprogress;
		}
		public void DoTheAsyncTask()
		{
			// Introduce an artificial delay to simulate a delayed 
			// asynchronous task. Make this greater than the 
			// AsyncTimeout property.
			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 = "Beginning async task.";

			_dlgt = new AsyncTaskDelegate(DoTheAsyncTask);
			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 = "Asynchronous task completed.";
			_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 = "Ansynchronous task failed to complete " +
				"because it exceeded the AsyncTimeout parameter.";
		}
	}
}


.NET Framework

Compatible con: 4.5, 4, 3.5, 3.0, 2.0

Windows 8, Windows Server 2012, Windows 7, Windows Vista SP2, Windows Server 2008 (no se admite el rol Server Core), Windows Server 2008 R2 (se admite el rol Server Core con SP1 o versiones posteriores; no se admite Itanium)

.NET Framework no admite todas las versiones de todas las plataformas. Para obtener una lista de las versiones compatibles, vea Requisitos de sistema de .NET Framework.
¿Te ha resultado útil?
(Caracteres restantes: 1500)

Adiciones de comunidad

AGREGAR
© 2013 Microsoft. Reservados todos los derechos.