基于使用BeginInvoke,EndInvoke異步調用委托的實現(xiàn)代碼
更新時間:2013年05月18日 11:52:31 作者:
本篇文章是對使用BeginInvoke,EndInvoke異步調用委托的實現(xiàn)代碼進行了分析介紹,需要的朋友參考下
復制代碼 代碼如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Main ThreadId = " + Thread.CurrentThread.ManagedThreadId);
//給委托賦值
Func<long, long> delegateMethod = new Func<long, long>(CalcSum);
//異步執(zhí)行委托,這里把委托本身作為asyncState對象傳進去,在回調函數(shù)中需要使用委托的EndInvoke來獲得結果
delegateMethod.BeginInvoke(200, DoneCallback, delegateMethod);
//異步執(zhí)行委托,拋出異常
delegateMethod.BeginInvoke(10000000000, DoneCallback, delegateMethod);
Console.ReadLine();
}
//委托回調函數(shù)
static void DoneCallback(IAsyncResult asyncResult)
{
//到這兒委托已經(jīng)在異步線程中執(zhí)行完畢
Console.WriteLine("DoneCallback ThreadId = " + Thread.CurrentThread.ManagedThreadId);
Func<long, long> method = (Func<long, long>)asyncResult.AsyncState;
//委托執(zhí)行的異常會在EndInvoke時拋出來
try {
//使用BeginInvoke時傳入委托的EndInvoke獲得計算結果,這時候計算結果已經(jīng)出來了,有異常的話也在這兒拋出來
long sum = method.EndInvoke(asyncResult);
Console.WriteLine("sum = {0}",sum);
}
catch (OverflowException)
{
Console.WriteLine("運算溢出了");
}
}
//委托方法
static long CalcSum(long topLimit)
{
//委托在另一個線程中開始執(zhí)行
Console.WriteLine("Calc ThreadId = " + Thread.CurrentThread.ManagedThreadId);
checked
{
long result = 0;
for (long i = 0; i < topLimit; i++)
{
result += i;
}
return result;
}
}
}
}
相關文章
C#實體對象序列化成Json并讓字段的首字母小寫的兩種解決方法
這篇文章主要介紹了C#實體對象序列化成Json并讓字段的首字母小寫的兩種方法,在這兩種方法中小編比較推薦使用第二種方法,需要的朋友可以參考下2018-06-06
C#使用EF連接PGSql數(shù)據(jù)庫的完整步驟
這篇文章主要給大家介紹了關于C#使用EF連接PGSql數(shù)據(jù)庫的相關資料,文中通過示例代碼介紹的非常詳細,需要的朋友可以參考借鑒,下面隨著小編來一起學習學習吧2019-01-01

