PageAsyncTask PageAsyncTask PageAsyncTask PageAsyncTask Class

定義

包含註冊到網頁之非同步工作的資訊。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
繼承
PageAsyncTaskPageAsyncTaskPageAsyncTaskPageAsyncTask

範例

下列程式碼範例會在頁面上註冊三個非同步工作, 並以平行方式執行它們。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

備註

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物件必須RegisterAsyncTask透過方法向頁面註冊。A 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. 方法也可以在事件之前用來啟動工作PreRenderCompleteExecuteRegisteredAsyncTasksThe 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" %>

建構函式

PageAsyncTask(BeginEventHandler, EndEventHandler, EndEventHandler, Object) PageAsyncTask(BeginEventHandler, EndEventHandler, EndEventHandler, Object) PageAsyncTask(BeginEventHandler, EndEventHandler, EndEventHandler, Object) 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(BeginEventHandler, EndEventHandler, EndEventHandler, Object, Boolean) PageAsyncTask(BeginEventHandler, EndEventHandler, EndEventHandler, Object, Boolean) 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(Func<CancellationToken,Task>) PageAsyncTask(Func<CancellationToken,Task>) 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(Func<Task>) PageAsyncTask(Func<Task>) PageAsyncTask(Func<Task>)

使用可處理工作的事件處理常式,初始化 PageAsyncTask 類別的新執行個體。Initializes a new instance of the PageAsyncTask class using an event handler that enables the task to be handled.

屬性

BeginHandler BeginHandler BeginHandler BeginHandler

取得當開始非同步工作時所要呼叫的方法。Gets the method to call when beginning an asynchronous task.

EndHandler EndHandler EndHandler EndHandler

取得當工作在逾時期限內成功完成時所要呼叫的方法。Gets the method to call when the task completes successfully within the time-out period.

ExecuteInParallel ExecuteInParallel ExecuteInParallel ExecuteInParallel

取得值,指出工作是否可以和其他工作平行處理。Gets a value that indicates whether the task can be processed in parallel with other tasks.

State State State State

取得會表示工作狀態的物件。Gets an object that represents the state of the task.

TimeoutHandler TimeoutHandler TimeoutHandler TimeoutHandler

取得當工作未在逾時期限內成功完成時所要呼叫的方法。Gets the method to call when the task does not complete successfully within the time-out period.

方法

Equals(Object) Equals(Object) Equals(Object) Equals(Object)

判斷指定的物件是否等於目前的物件。Determines whether the specified object is equal to the current object.

(Inherited from Object)
GetHashCode() GetHashCode() GetHashCode() GetHashCode()

做為預設雜湊函式。Serves as the default hash function.

(Inherited from Object)
GetType() GetType() GetType() GetType()

取得目前執行個體的 TypeGets the Type of the current instance.

(Inherited from Object)
MemberwiseClone() MemberwiseClone() MemberwiseClone() MemberwiseClone()

建立目前 Object 的淺層複本 (Shallow Copy)。Creates a shallow copy of the current Object.

(Inherited from Object)
ToString() ToString() ToString() ToString()

傳回代表目前物件的字串。Returns a string that represents the current object.

(Inherited from Object)

適用於