文章详情

  • 游戏榜单
  • 软件榜单
关闭导航
热搜榜
热门下载
热门标签
php爱好者> php文档>C#的异步调用

C#的异步调用

时间:2010-09-01  来源:让大家开心的人

  使用异步调用,某些时候可以提高性能,比如说写日志,对数据库进行操作的时候就可以使用异步操作的方式。这种方式相当于多线程并发运行,所以性能会有所提升。我后面会发篇随笔来使用异步调用的方法写日志。code:

  using System;

  namespace Sandals.Demo.AsynchronousCall

  {

  public static class AsyncDemo

  {

  //声明委托

  private delegate string AsyncMethodCalledEventHander(int duration, out int threadId);

  //create an instance of the delegate

  private static AsyncMethodCalledEventHander eventHandler = new AsyncMethodCalledEventHander(MethodForAsyncCall);

  /// <summary>

  /// The method to be executed asynchronously

  /// </summary>www.qichepeijian.com

  /// <param name="duration">sleep duration for thread</param>

  /// <param name="threadId">current thread id</param>

  /// <returns></returns>

  private static string MethodForAsyncCall(int duration, out int threadId)

  {

  Console.WriteLine("MethodForAsyncCall begin execute... ");

  System.Threading.Thread.Sleep(duration);

  threadId = System.Threading.Thread.CurrentThread.ManagedThreadId;

  return String.Format("my execute time was {0} ", duration);

  }

  /// <summary>

  /// this method for executing asyc method

  /// </summary>

  /// <param name="duration"></param>

  /// <returns></returns>

  public static IAsyncResult BeingRun(int duration)

  {

  int dumy;

  IAsyncResult result = eventHandler.BeginInvoke(duration, out dumy, null, null);

  return result;

  }

  /// <summary>

  /// this methiod end the asyc method

  /// <summary>

  /// <param name="threadId"></param>

  /// <param name="ar"></param>

  /// <returns></returns>

  public static string EndRun(out int threadId, IAsyncResult ar)

  {

  if (ar == null)

  throw new NullReferenceException("parameter ar can not be a null");

  return eventHandler.EndInvoke(out threadId, ar);

  }

  }

  class Program

  {

  static void Main(string[] args)

  {

  IAsyncResult result = AsyncDemo.BeingRun(10000);

  Console.WriteLine("the thread {0} continue to execute", System.Threading.Thread.CurrentThread.ManagedThreadId);

  Console.WriteLine("the thread {0} begin to sleep, date: {1}", System.Threading.Thread.CurrentThread.ManagedThreadId, DateTime.Now);

  System.Threading.Thread.Sleep(3000);

  Console.WriteLine("the thread {0} sleep end, date: {1}", System.Threading.Thread.CurrentThread.ManagedThreadId, DateTime.Now);

  int threadId = 0;

  Console.WriteLine("call the mothod to end the ansychronous method");

  Console.WriteLine("asynchronous method return value: {0}. thread id: {1}", AsyncDemo.EndRun(out threadId, result), threadId);

  }

  }

  }

相关阅读 更多 +
排行榜 更多 +
辰域智控app

辰域智控app

系统工具 下载
网医联盟app

网医联盟app

运动健身 下载
汇丰汇选App

汇丰汇选App

金融理财 下载