基于使用BeginInvoke,EndInvoke異步調(diào)用委托的實(shí)現(xiàn)代碼
更新時(shí)間:2013年05月18日 11:52:31 作者:
本篇文章是對(duì)使用BeginInvoke,EndInvoke異步調(diào)用委托的實(shí)現(xiàn)代碼進(jìn)行了分析介紹,需要的朋友參考下
復(fù)制代碼 代碼如下:
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對(duì)象傳進(jìn)去,在回調(diào)函數(shù)中需要使用委托的EndInvoke來獲得結(jié)果
delegateMethod.BeginInvoke(200, DoneCallback, delegateMethod);
//異步執(zhí)行委托,拋出異常
delegateMethod.BeginInvoke(10000000000, DoneCallback, delegateMethod);
Console.ReadLine();
}
//委托回調(diào)函數(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í)行的異常會(huì)在EndInvoke時(shí)拋出來
try {
//使用BeginInvoke時(shí)傳入委托的EndInvoke獲得計(jì)算結(jié)果,這時(shí)候計(jì)算結(jié)果已經(jīng)出來了,有異常的話也在這兒拋出來
long sum = method.EndInvoke(asyncResult);
Console.WriteLine("sum = {0}",sum);
}
catch (OverflowException)
{
Console.WriteLine("運(yùn)算溢出了");
}
}
//委托方法
static long CalcSum(long topLimit)
{
//委托在另一個(gè)線程中開始執(zhí)行
Console.WriteLine("Calc ThreadId = " + Thread.CurrentThread.ManagedThreadId);
checked
{
long result = 0;
for (long i = 0; i < topLimit; i++)
{
result += i;
}
return result;
}
}
}
}
相關(guān)文章
C#編程實(shí)現(xiàn)簡(jiǎn)易圖片瀏覽器的方法
這篇文章主要介紹了C#編程實(shí)現(xiàn)簡(jiǎn)易圖片瀏覽器的方法,涉及C#基于WinForm操作圖片實(shí)現(xiàn)預(yù)覽功能的相關(guān)技巧,具有一定參考借鑒價(jià)值,需要的朋友可以參考下2015-11-11
C#緩存之SqlCacheDependency用法實(shí)例總結(jié)
這篇文章主要介紹了C#緩存之SqlCacheDependency用法,在C#程序設(shè)計(jì)中有一定的實(shí)用價(jià)值,需要的朋友可以參考下2014-08-08
C# PictureBox圖片控件實(shí)現(xiàn)圖片交換
在c#中可以使用PictureBox控件來呈現(xiàn)圖像,本文主要介紹了C# PictureBox實(shí)現(xiàn)圖片交換,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-06-06
C#使用MD5算法對(duì)密碼進(jìn)行加密的示例代碼
MD5(Message Digest Algorithm 5)是一種被廣泛使用的“消息-摘要算法”,“消息-摘要算法”實(shí)際上就是一個(gè)單項(xiàng)散列函數(shù),數(shù)據(jù)塊經(jīng)過單向散列函數(shù)得到一個(gè)固定長(zhǎng)度的散列值,本文給大家介紹了C#使用MD5算法對(duì)密碼進(jìn)行加密,需要的朋友可以參考下2024-03-03
C#的FileInfo類實(shí)現(xiàn)文件操作實(shí)例
這篇文章主要介紹了C#的FileInfo類實(shí)現(xiàn)文件操作實(shí)例,比較實(shí)用的功能,需要的朋友可以參考下2014-07-07

