PageAsyncTask Class

Definition

包含有关注册到页的异步任务的信息。Contains information about an asynchronous task registered to a page. 此类不能被继承。This class cannot be inherited.

public ref class PageAsyncTask sealed
public sealed class PageAsyncTask
type PageAsyncTask = class
Public NotInheritable Class PageAsyncTask
Inheritance
PageAsyncTask

Examples

下面的代码示例向页面注册三个异步任务并并行执行它们。The following code example registers three asynchronous tasks to a page and executes them in parallel. 每个任务都调用一个方法, 该方法仅导致线程进入5秒。Each task calls a method that merely causes the thread to sleep for 5 seconds.

<%@ 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

Remarks

ASP.NET 版本2.0 允许你向页面注册多个任务, 并在呈现页面之前以异步方式运行这些任务。ASP.NET version 2.0 allows you to register multiple tasks to a page and run them asynchronously prior to rendering the page. 你可以指定在任务速度缓慢且不希望其他进程在执行时进行关联的情况下, 以异步方式运行任务。You might specify that a task be run asynchronously if it is a slow process and you do not want other processes to be tied up while it is executing. 异步任务可以并行执行, 也可以按顺序执行。The asynchronous tasks can be executed in parallel or sequentially.

必须通过方法向页面注册对象。 PageAsyncTask RegisterAsyncTaskA PageAsyncTask object must be registered to the page through the RegisterAsyncTask method. 不需要异步处理页本身即可执行异步任务。The page itself does not have to be processed asynchronously to execute asynchronous tasks. 您可以将Async属性设置true为 (如下面的代码示例所示), 或false在页指令上进行异步处理的异步任务。You can set the Async attribute to either true (as shown in the following code example) or false on the page directive and the asynchronous tasks will still be processed asynchronously:

<%@ Page Async="true" %>

当特性设置为false时, 将阻止执行页的线程, 直到所有异步任务完成。 AsyncWhen the Async attribute is set to false, the thread that executes the page will be blocked until all asynchronous tasks are complete.

如果尚未执行事件, 则PreRenderComplete在该事件之前注册的任何异步任务都将自动执行。Any asynchronous tasks registered before the PreRenderComplete event will be executed automatically by the page if they have not already been executed. PreRenderComplete 必须ExecuteRegisteredAsyncTasks通过方法显式执行在事件之后注册的异步任务。Those asynchronous tasks registered after the PreRenderComplete event must be executed explicitly through the ExecuteRegisteredAsyncTasks method. 方法还可用于在PreRenderComplete事件之前启动任务。 ExecuteRegisteredAsyncTasksThe ExecuteRegisteredAsyncTasks method can also be used to start tasks before the PreRenderComplete event. ExecuteRegisteredAsyncTasks方法在尚未执行的页上执行所有已注册的异步任务。The ExecuteRegisteredAsyncTasks method executes all the registered asynchronous tasks on the page that have not been executed.

默认情况下, 如果异步任务在45秒内未完成, 则会超时。By default, an asynchronous task will time out if it has not completed within 45 seconds. 您可以在 web.config 文件或 page 指令中指定不同的超时值。You can specify a different time-out value in either the Web.config file or the page directive. Web.config <pages>文件的节asyncTimeout包含特性, 如下所示。The <pages> section of the Web.config file contains an asyncTimeout attribute, as shown below.

<system.web>

<pages asyncTimeout="30">

</pages>

</system.web>

Page 指令包含AsyncTimeout特性。The page directive contains an AsyncTimeout attribute.

<%@ Page AsyncTimeout="30" %>

Constructors

PageAsyncTask(BeginEventHandler, EndEventHandler, EndEventHandler, Object)

使用并行执行的默认值初始化 PageAsyncTask 类的新实例。Initializes a new instance of the PageAsyncTask class using the default value for executing in parallel.

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

使用并行执行的指定值初始化 PageAsyncTask 类的新实例。Initializes a new instance of the PageAsyncTask class using the specified value for executing in parallel.

PageAsyncTask(Func<CancellationToken,Task>)

使用能取消任务的事件处理程序初始化 PageAsyncTask 类的新实例。Initializes a new instance of the PageAsyncTask class using an event handler that enables the task to be canceled.

PageAsyncTask(Func<Task>)

使用能处理任务的事件处理程序初始化 PageAsyncTask 类的新实例。Initializes a new instance of the PageAsyncTask class using an event handler that enables the task to be handled.

Properties

BeginHandler

获取当异步任务开始时要调用的方法。Gets the method to call when beginning an asynchronous task.

EndHandler

获取当任务在超时期内成功完成时要调用的方法。Gets the method to call when the task completes successfully within the time-out period.

ExecuteInParallel

获取一个值,该值指示任务能否与其他任务并行处理。Gets a value that indicates whether the task can be processed in parallel with other tasks.

State

获取表示任务状态的对象。Gets an object that represents the state of the task.

TimeoutHandler

获取当任务未在超时期内成功完成时要调用的方法。Gets the method to call when the task does not complete successfully within the time-out period.

Methods

Equals(Object)

确定指定的对象是否等于当前对象。Determines whether the specified object is equal to the current object.

(Inherited from Object)
GetHashCode()

作为默认哈希函数。Serves as the default hash function.

(Inherited from Object)
GetType()

获取当前实例的 TypeGets the Type of the current instance.

(Inherited from Object)
MemberwiseClone()

创建当前 Object 的浅表副本。Creates a shallow copy of the current Object.

(Inherited from Object)
ToString()

返回表示当前对象的字符串。Returns a string that represents the current object.

(Inherited from Object)

Applies to