使用異步方式調(diào)用同步方法(實例詳解)
說明:
.NET Compact Framework 中不支持異步委托調(diào)用,也就是 BeginInvoke 和 EndInvoke 方法。
BeginInvoke 方法啟動異步調(diào)用。該方法與您需要異步執(zhí)行的方法具有相同的參數(shù),還有另外兩個可選參數(shù)。第一個參數(shù)是一個 AsyncCallback 委托,該委托引用在異步調(diào)用完成時要調(diào)用的方法。第二個參數(shù)是一個用戶定義的對象,該對象將信息傳入回調(diào)方法。BeginInvoke 會立即返回,而不等待異步調(diào)用完成。BeginInvoke 返回一個可用于監(jiān)視異步調(diào)用進度的 IAsyncResult。
EndInvoke 方法檢索異步調(diào)用的結(jié)果。在調(diào)用 BeginInvoke 之后隨時可以調(diào)用該方法。如果異步調(diào)用尚未完成,則 EndInvoke 會一直阻止調(diào)用線程,直到異步調(diào)用完成。EndInvoke 的參數(shù)包括您需要異步執(zhí)行的方法的 out 和 ref 參數(shù)(在 Visual Basic 中為 <Out> ByRef 和 ByRef)以及由 BeginInvoke 返回的 IAsyncResult。
說明:
Visual Studio 2005 中的 IntelliSense 功能顯示 BeginInvoke 和 EndInvoke 的參數(shù)。如果您沒有使用 Visual Studio 或類似工具,或您使用的是帶有 Visual Studio 2005 的 C#,請參見 異步編程概述 以獲取為這些方法定義的參數(shù)的說明。
本主題中的代碼示例演示了使用 BeginInvoke 和 EndInvoke 進行異步調(diào)用的四種常用方法。調(diào)用 BeginInvoke 之后,您可以執(zhí)行下列操作:
進行某些操作,然后調(diào)用 EndInvoke 一直阻止到調(diào)用完成。
使用 IAsyncResult.AsyncWaitHandle 屬性獲取 WaitHandle,使用其 WaitOne 方法一直阻止執(zhí)行直到發(fā)出 WaitHandle 信號,然后調(diào)用 EndInvoke。
輪詢由 BeginInvoke 返回的 IAsyncResult,以確定異步調(diào)用何時完成,然后調(diào)用 EndInvoke。
將用于回調(diào)方法的委托傳遞給 BeginInvoke。異步調(diào)用完成后,將在 ThreadPool 線程上執(zhí)行該方法。回調(diào)方法調(diào)用 EndInvoke。
重要說明:
無論您使用何種方法,都要調(diào)用 EndInvoke 來完成異步調(diào)用。
定義測試方法和異步委托
下面的代碼示例演示異步調(diào)用同一個長時間運行的方法 TestMethod 的各種方式。TestMethod 方法會顯示一條控制臺消息,說明該方法已開始處理,休眠了幾秒鐘,然后結(jié)束。TestMethod 有一個 out 參數(shù),該參數(shù)用于演示此種參數(shù)添加到 BeginInvoke 和 EndInvoke 的簽名中的方式。您可以按同樣的方式處理 ref 參數(shù)。
下面的代碼示例演示 TestMethod 的定義和名為 AsyncMethodCaller 的、可用來異步調(diào)用 TestMethod 的委托。若要編譯代碼示例,必須包括 TestMethod 的定義和 AsyncMethodCaller 委托。
C#
using System;
using System.Threading;
namespace AsyncTest
{
public class AsyncDemo
{
//方法一
public string TestMethod(int callDuration, out int threadId)
{
Console.WriteLine("Test method begins.");
Thread.Sleep(callDuration);
threadId = Thread.CurrentThread.ManagedThreadId;
return String.Format("My call time was {0}.", callDuration.ToString());
}
//方法二
public float Addxy(float x, float y)
{
return x * y;
}
}
//定義兩個對應(yīng)于方法的委托,參數(shù)同方法一致,委托的聲明寫在調(diào)用類里也是一樣的,不限
public delegate string AsyncMethodCaller(int callDuration, out int threadId);
public delegate float AsyncMethodCaller2(float x, float y);
}
使用 EndInvoke 等待異步調(diào)用
異步執(zhí)行方法的最簡單方式是通過調(diào)用委托的 BeginInvoke 方法來開始執(zhí)行方法,在主線程上執(zhí)行一些操作,然后調(diào)用委托的 EndInvoke 方法。EndInvoke 可能會阻止調(diào)用線程,因為該方法直到異步調(diào)用完成后才返回。這種方式非常適合執(zhí)行文件或網(wǎng)絡(luò)操作。
重要說明:
因為 EndInvoke 可能會阻塞,所以不應(yīng)從服務(wù)于用戶界面的線程調(diào)用該方法。
C#
using System;
using System.Threading;
namespace AsyncTest
{
public class AsyncMain
{
public static void Main()
{
// The asynchronous method puts the thread id here.
int threadId;
//實例化.
AsyncDemo ad = new AsyncDemo();
// 定義委托
AsyncMethodCaller caller = new AsyncMethodCaller(ad.TestMethod);
//通過委托調(diào)用方法,回調(diào)函數(shù)為null
IAsyncResult result = caller.BeginInvoke(3000,
out threadId, null, null);
Thread.Sleep(0);
Console.WriteLine("Main thread {0} does some work.",
Thread.CurrentThread.ManagedThreadId);
// Call EndInvoke to wait for the asynchronous call to complete,會阻塞
// and to retrieve the results.
string returnValue = caller.EndInvoke(out threadId, result);
Console.WriteLine("The call executed on thread {0}, with return value \"{1}\".",
threadId, returnValue);
}
}
}
使用 WaitHandle 等待異步調(diào)用
您可以使用由 BeginInvoke 返回的 IAsyncResult 的 AsyncWaitHandle 屬性來獲取 WaitHandle。異步調(diào)用完成時會發(fā)出 WaitHandle 信號,而您可以通過調(diào)用 WaitOne 方法等待它。
如果您使用 WaitHandle,則在異步調(diào)用完成之前或之后,但在通過調(diào)用 EndInvoke 檢索結(jié)果之前,還可以執(zhí)行其他處理。
說明:
調(diào)用 EndInvoke 時不會自動關(guān)閉等待句柄。如果釋放對等待句柄的所有引用,則當(dāng)垃圾回收功能回收等待句柄時,將釋放系統(tǒng)資源。若要在等待句柄使用完畢后立即釋放系統(tǒng)資源,請調(diào)用 WaitHandle.Close 方法來釋放等待句柄。顯式釋放可釋放的對象時,垃圾回收的工作效率會更高。
C#
using System;
using System.Threading;
namespace AsyncTest
{
public class AsyncMain
{
static void Main()
{
// The asynchronous method puts the thread id here.
int threadId;
//實例化
AsyncDemo ad = new AsyncDemo();
//定義委托.
AsyncMethodCaller caller = new AsyncMethodCaller(ad.TestMethod);
//調(diào)用
IAsyncResult result = caller.BeginInvoke(3000,
out threadId, null, null);
Thread.Sleep(0);
Console.WriteLine("Main thread {0} does some work.",
Thread.CurrentThread.ManagedThreadId);
// Wait for the WaitHandle to become signaled.
result.AsyncWaitHandle.WaitOne();
// Perform additional processing here.
// Call EndInvoke to retrieve the results.
string returnValue = caller.EndInvoke(out threadId, result);
// Close the wait handle.
result.AsyncWaitHandle.Close();
Console.WriteLine("The call executed on thread {0}, with return value \"{1}\".",
threadId, returnValue);
}
}
}
/*輸出如下:
Main thread 1 does some work.
Test method begins.
The call executed on thread 3, with return value "My call time was 3000.".
*/
輪詢異步調(diào)用完成
您可以使用由 BeginInvoke 返回的 IAsyncResult 的 IsCompleted 屬性來發(fā)現(xiàn)異步調(diào)用何時完成。從用戶界面的服務(wù)線程中進行異步調(diào)用時可以執(zhí)行此操作。輪詢完成允許調(diào)用線程在異步調(diào)用在 ThreadPool 線程上執(zhí)行時繼續(xù)執(zhí)行。
C#C++VB
using System;
using System.Threading;
namespace AsyncTest
{
public class AsyncMain
{
static void Main() {
// The asynchronous method puts the thread id here.
int threadId;
//實例化.
AsyncDemo ad = new AsyncDemo();
//聲明委托
AsyncMethodCaller caller = new AsyncMethodCaller(ad.TestMethod);
//調(diào)用.
IAsyncResult result = caller.BeginInvoke(3000,
out threadId, null, null);
//輪詢.
while(result.IsCompleted == false) {
Thread.Sleep(250);
Console.Write(".");
}
//取結(jié)果.
string returnValue = caller.EndInvoke(out threadId, result);
Console.WriteLine("\nThe call executed on thread {0}, with return value \"{1}\".",
threadId, returnValue);
}
}
}
/* 輸出:
Test method begins.
.............
The call executed on thread 3, with return value "My call time was 3000.".
*/
異步調(diào)用完成時執(zhí)行回調(diào)方法
如果啟動異步調(diào)用的線程不需要是處理結(jié)果的線程,則可以在調(diào)用完成時執(zhí)行回調(diào)方法?;卣{(diào)方法在 ThreadPool 線程上執(zhí)行。
若要使用回調(diào)方法,必須將表示回調(diào)方法的 AsyncCallback 委托傳遞給 BeginInvoke。也可以傳遞包含回調(diào)方法要使用的信息的對象。在回調(diào)方法中,可以將 IAsyncResult(回調(diào)方法的唯一參數(shù))強制轉(zhuǎn)換為 AsyncResult 對象。然后,可以使用 AsyncResult.AsyncDelegate 屬性獲取已用于啟動調(diào)用的委托,以便可以調(diào)用 EndInvoke。
有關(guān)示例的說明:
TestMethod 的 threadId 參數(shù)為 out 參數(shù)(在 Visual Basic 中為 <Out> ByRef),因此 TestMethod 從不使用該參數(shù)的輸入值。會將一個虛擬變量傳遞給 BeginInvoke 調(diào)用。如果 threadId 參數(shù)為 ref 參數(shù)(在 Visual Basic 中為 ByRef),則該變量必須為類級別字段,這樣才能同時傳遞給 BeginInvoke 和 EndInvoke。
傳遞給 BeginInvoke 的狀態(tài)信息是一個格式字符串,回調(diào)方法使用該字符串來設(shè)置輸出消息的格式。因為作為類型 Object 進行傳遞,所以狀態(tài)信息必須強制轉(zhuǎn)換為正確的類型才能被使用。
回調(diào)是在 ThreadPool 線程上進行的。ThreadPool 線程是后臺線程,這些線程不會在主線程結(jié)束后保持應(yīng)用程序的運行,因此示例的主線程必須休眠足夠長的時間以便回調(diào)完成。
C#
using System;
using System.Threading;
using System.Runtime.Remoting.Messaging;
namespace AsyncTest
{
public class AsyncMain
{
static void Main()
{
//實例化類.
AsyncDemo ad = new AsyncDemo();
//實例兩個不同的委托,分別對應(yīng)不同的方法.
AsyncMethodCaller caller = new AsyncMethodCaller(ad.TestMethod);
AsyncMethodCaller2 caller2 = new AsyncMethodCaller2(ad.Addxy);
// The threadId parameter of TestMethod is an out parameter, so
// its input value is never used by TestMethod. Therefore, a dummy
// variable can be passed to the BeginInvoke call. If the threadId
// parameter were a ref parameter, it would have to be a class-
// level field so that it could be passed to both BeginInvoke and
// EndInvoke.
int dummy = 0;
// 調(diào)用時指定回調(diào)方法,在異步執(zhí)行完后會自動調(diào)用該方法,用來取得執(zhí)行的結(jié)果
IAsyncResult result = caller.BeginInvoke(3000,
out dummy,
new AsyncCallback(CallbackMethod),
"The call executed on thread {0}, with return value \"{1}\".");
caller2.BeginInvoke(2, 3, CallbackMethod2, "this is add");
Console.WriteLine("The main thread {0} continues to execute...",
Thread.CurrentThread.ManagedThreadId);
Thread.Sleep(4000);
Console.WriteLine("The main thread ends.");
}
// The callback method must have the same signature as the
// AsyncCallback delegate.
private void CallbackMethod(IAsyncResult ar)
{
// Retrieve the delegate.
AsyncResult result = (AsyncResult) ar;
//強制轉(zhuǎn)換成對應(yīng)的委托對象
AsyncMethodCaller caller = (AsyncMethodCaller) result.AsyncDelegate;
// Retrieve the format string that was passed as state
// information.
string formatString = (string) ar.AsyncState;
// Define a variable to receive the value of the out parameter.
// If the parameter were ref rather than out then it would have to
// be a class-level field so it could also be passed to BeginInvoke.
int threadId = 0;
// Call EndInvoke to retrieve the results.
string returnValue = caller.EndInvoke(out threadId, ar);
// Use the format string to format the output message.
Console.WriteLine(formatString, threadId, returnValue);
}
private void CallbackMethod2(IAsyncResult ar)
{
// Retrieve the delegate.
AsyncResult result = (AsyncResult)ar;
//強制轉(zhuǎn)換成對應(yīng)的委托對象
AsyncMethodCaller2 caller = (AsyncMethodCaller2)result.AsyncDelegate;
// 取得狀態(tài)
string formatString = (string)ar.AsyncState;
//調(diào)用異步完成的方法,取得執(zhí)行結(jié)果
string returnValue = caller.EndInvoke(ar).ToString();
//此種方式是在windows應(yīng)用程序給控件賦值時用,因為在非創(chuàng)建線程不能操作控件
this.Invoke(new Action<string>((u) => tb_datainfo.Text += u), returnValue);
//tb_datainfo.Text = caller.EndInvoke(out threadId, ar);
// Use the format string to format the output message.
//Console.WriteLine(formatString, threadId, returnValue);
}
}
}
}
相關(guān)文章
C#數(shù)組學(xué)習(xí)相關(guān)資料整理
最近開始學(xué)習(xí)c#,并有幸接觸到了數(shù)組方便的操作,感覺確實不錯,這里簡單的整理下c#相關(guān)的學(xué)習(xí)資料,方便大家學(xué)習(xí)2012-09-09C#異步迭代IAsyncEnumerable應(yīng)用實現(xiàn)
IAsyncEnumerable可以來實現(xiàn)異步迭代,本文就主要介紹了C#異步迭代IAsyncEnumerable應(yīng)用實現(xiàn),具有一定的參考價值,感興趣的小伙伴們可以參考一下2021-06-06C#實現(xiàn)在控制臺輸出當(dāng)前系統(tǒng)時間的方法
這篇文章主要介紹了C#實現(xiàn)在控制臺輸出當(dāng)前系統(tǒng)時間的方法,涉及C#時間函數(shù)DateTime.Now的使用方法,需要的朋友可以參考下2015-04-04