C# 的异步调用_C/C++语言_黑客防线网安服务器维护基地--Powered by WWW.RONGSEN.COM.CN

C# 的异步调用

作者:黑客防线网安C/C++教程基地 来源:黑客防线网安C/C++教程基地 浏览次数:0

黑客防线网安网讯:   使用异步调用,某些时候可以提高性能,比如说写日志,对数据库进行操作的时候就可以使用异步操作的方式。这种方式相当于多线程并发运行,所以性能会有所提升。我后面会发篇随笔来使用异步...
   使用异步调用某些时候可以提高性能比如说写日志,对数据库进行操作的时候就可以使用异步操作的方式这种方式相当于多线程并发运行,所以性能会有所提升我后面会发篇随笔来使用异步调用的方法写日志。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>
  /// <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);
  }
  }
  }
    黑客防线网安服务器维护方案本篇连接:http://www.rongsen.com.cn/show-15287-1.html
网站维护教程更新时间:2012-04-04 22:52:43  【打印此页】  【关闭
我要申请本站N点 | 黑客防线官网 |  
专业服务器维护及网站维护手工安全搭建环境,网站安全加固服务。黑客防线网安服务器维护基地招商进行中!QQ:29769479

footer  footer  footer  footer