How to call a function asynchronizly in C# # Page1- Delegate.begininvoke, endinvoke


BeginInvoke and EndInvoke

we use four ways to process the asynchronozed call.i.e. EndInvoke,WaitHandler,IsComplete,callbackfunction.they are properties of IAsyncresult.

  1. we can see description from MSDN,

    The BeginInvoke method initiates the asynchronous call. It has the same parameters as the method that you want to execute asynchronously, plus two additional optional parameters. The first parameter is an AsyncCallback delegate that references a method to be called when the asynchronous call completes. The second parameter is a user-defined object that passes information into the callback method. BeginInvoke returns immediately and does not wait for the asynchronous call to complete. BeginInvoke returns an IAsyncResult, which can be used to monitor the progress of the asynchronous call.

    The EndInvoke method retrieves the results of the asynchronous call. It can be called any time after BeginInvoke. If the asynchronous call has not completed, EndInvoke blocks the calling thread until it completes. The parameters of EndInvoke include the out and ref parameters ( ByRef and ByRef in Visual Basic) of the method that you want to execute asynchronously, plus the IAsyncResult returned by BeginInvoke.

code example:

using System;
using System.Threading; namespace Examples.AdvancedProgramming.AsynchronousOperations
{
public class AsyncDemo
{
// The method to be executed asynchronously.
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());
}
}
// The delegate must have the same signature as the method
// it will call asynchronously.
public delegate string AsyncMethodCaller(int callDuration, out int threadId);
}
using System;
using System.Threading; namespace Examples.AdvancedProgramming.AsynchronousOperations
{
public class AsyncMain
{
public static void Main()
{
// The asynchronous method puts the thread id here.
int threadId; // Create an instance of the test class.
AsyncDemo ad = new AsyncDemo(); // Create the delegate.
AsyncMethodCaller caller = new AsyncMethodCaller(ad.TestMethod); // Initiate the asychronous call.
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);
}
}
} /* This example produces output similar to the following: Main thread 1 does some work.
Test method begins.
The call executed on thread 3, with return value "My call time was 3000.".
*/

code example : Waiting for an Asynchronous Call with WaitHandle

using System;
using System.Threading; namespace Examples.AdvancedProgramming.AsynchronousOperations
{
public class AsyncMain
{
static void Main()
{
// The asynchronous method puts the thread id here.
int threadId; // Create an instance of the test class.
AsyncDemo ad = new AsyncDemo(); // Create the delegate.
AsyncMethodCaller caller = new AsyncMethodCaller(ad.TestMethod); // Initiate the asychronous call.
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);
}
}
} /* This example produces output similar to the following: Main thread 1 does some work.
Test method begins.
The call executed on thread 3, with return value "My call time was 3000.".
*/

code example 3: Polling for Asynchronous Call Completion

You can use the IsCompleted property of the IAsyncResult returned by BeginInvoke to discover when the asynchronous call completes. You might do this when making the asynchronous call from a thread that services the user interface. Polling for completion allows the calling thread to continue executing while the asynchronous call executes on a ThreadPool thread.

 using System;
using System.Threading; namespace Examples.AdvancedProgramming.AsynchronousOperations
{
public class AsyncMain
{
static void Main() {
// The asynchronous method puts the thread id here.
int threadId; // Create an instance of the test class.
AsyncDemo ad = new AsyncDemo(); // Create the delegate.
AsyncMethodCaller caller = new AsyncMethodCaller(ad.TestMethod); // Initiate the asychronous call.
IAsyncResult result = caller.BeginInvoke(3000,
out threadId, null, null); // Poll while simulating work.
while(result.IsCompleted == false) {
Thread.Sleep(250);
Console.Write(".");
} // Call EndInvoke to retrieve the results.
string returnValue = caller.EndInvoke(out threadId, result); Console.WriteLine("\nThe call executed on thread {0}, with return value \"{1}\".",
threadId, returnValue);
}
}
} /* This example produces output similar to the following: Test method begins.
.............
The call executed on thread 3, with return value "My call time was 3000.".
*/

code example4: Executing a Callback Method When an Asynchronous Call Completes

If the thread that initiates the asynchronous call does not need to be the thread that processes the results, you can execute a callback method when the call completes. The callback method is executed on a ThreadPool thread.

To use a callback method, you must pass BeginInvoke an AsyncCallback delegate that represents the callback method. You can also pass an object that contains information to be used by the callback method. In the callback method, you can cast the IAsyncResult, which is the only parameter of the callback method, to an AsyncResult object. You can then use the AsyncResult.AsyncDelegate property to get the delegate that was used to initiate the call so that you can call EndInvoke.

using System;
using System.Threading;
using System.Runtime.Remoting.Messaging; namespace Examples.AdvancedProgramming.AsynchronousOperations
{
public class AsyncMain
{
static void Main()
{
// Create an instance of the test class.
AsyncDemo ad = new AsyncDemo(); // Create the delegate.
AsyncMethodCaller caller = new AsyncMethodCaller(ad.TestMethod); // 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; // Initiate the asynchronous call, passing three seconds (3000 ms)
// for the callDuration parameter of TestMethod; a dummy variable
// for the out parameter (threadId); the callback delegate; and
// state information that can be retrieved by the callback method.
// In this case, the state information is a string that can be used
// to format a console message.
IAsyncResult result = caller.BeginInvoke(3000,
out dummy,
new AsyncCallback(CallbackMethod),
"The call executed on thread {0}, with return value \"{1}\"."); Console.WriteLine("The main thread {0} continues to execute...",
Thread.CurrentThread.ManagedThreadId); // The callback is made on a ThreadPool thread. ThreadPool threads
// are background threads, which do not keep the application running
// if the main thread ends. Comment out the next line to demonstrate
// this.
Thread.Sleep(4000); Console.WriteLine("The main thread ends.");
} // The callback method must have the same signature as the
// AsyncCallback delegate.
static void CallbackMethod(IAsyncResult ar)
{
// Retrieve the delegate.
AsyncResult result = (AsyncResult) ar;
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);
}
}
} /* This example produces output similar to the following: The main thread 1 continues to execute...
Test method begins.
The call executed on thread 3, with return value "My call time was 3000.".
The main thread ends.
*/
  1. Some reference link about concept: AsyncCallback, IAsyncResult

  2. Waiting for an Asynchronous Call with WaitHandle.

You can obtain a WaitHandle by using the AsyncWaitHandle property of the IAsyncResult returned by BeginInvoke. The WaitHandle is signaled when the asynchronous call completes, and you can wait for it by calling the WaitOne method.

If you use a WaitHandle, you can perform additional processing before or after the asynchronous call completes, but before calling EndInvoke to retrieve the results.

we can refer AsyncWaitHandle, WaitHandle

How to Call a synchronize function asynchronizly in C#的更多相关文章

  1. HOW TO: Synchronize changes when completing a P2V or V2V with VMware vCenter Converter Standalone 5.1

    http://www.experts-exchange.com/Software/VMWare/A_11489-HOW-TO-Synchronize-changes-when-completing-a ...

  2. Neural Style学习2——环境安装

    neural-style Installation This guide will walk you through the setup for neural-style on Ubuntu. Ste ...

  3. murri

    github: https://github.com/haltu/muuri 官网:https://haltu.github.io/muuri/   安装 npm install murri —sav ...

  4. 通过百度echarts实现数据图表展示功能

    现在我们在工作中,在开发中都会或多或少的用到图表统计数据显示给用户.通过图表可以很直观的,直接的将数据呈现出来.这里我就介绍说一下利用百度开源的echarts图表技术实现的具体功能. 1.对于不太理解 ...

  5. Delphi中线程类TThread实现多线程编程2---事件、临界区、Synchronize、WaitFor……

    接着上文介绍TThread. 现在开始说明 Synchronize和WaitFor 但是在介绍这两个函数之前,需要先介绍另外两个线程同步技术:事件和临界区 事件(Event) 事件(Event)与De ...

  6. Synchronization in Delphi TThread class : Synchronize, Queue

    http://embarcadero.newsgroups.archived.at/public.delphi.rtl/201112/1112035763.html > Hi,>> ...

  7. AsyncCalls – Asynchronous function calls

    AsyncCalls – Asynchronous function callsWith AsyncCalls you can execute multiple functions at the sa ...

  8. Synchronize执行过程

    Synchronize执行过程及原理 在windows原生应用程序开发中,经常伴随多线程的使用,多线程开发很简单,难点就是在于线程的同步,在Delphi中提供了VC中不具备的一个过程Synchroni ...

  9. [React] Use the React Effect Hook in Function Components

    Similar to the State Hook, the Effect Hook is “first-class” in React and handy for performing side e ...

随机推荐

  1. 二模11day1解题报告

    T1.树的重量(weight) 给出一棵n个叶节点的树(但是有多组数据)以及n个节点之间的距离(最短距离...然而也只有一条路),求树的所有边权之和. 一开始完全没有思路啊...难道爆搜模拟??狂汗. ...

  2. 委托delegate使用方法

    允许传递一个类A的方法m给另一个类B的对象,使得类B的对象能够调用这个方法m,说白了就是可以把方法当作参数传递. class Program { //delegate的使用方法一 public del ...

  3. JavaScript高级 面向对象的程序设计 (一)《JavaScript高级程序设计(第三版)》

    创建对象 继承 面向对象的语言都有一个表示---类.通过类我们可以创建多个具有相同属性的对象.但是,在JS中并没有类的概念,所以JS的对象也和其他语言的对象不同. 对象的定义:无序的属性集合,其属性可 ...

  4. Ubuntu工具:vi编辑器

    Vi简介 Vi是“Visual interface”的简称,它在Linux上的地位就仿佛Edit程序在DOS上一样.它可以执行输出.删除.查找.替换.块操作等众多文本操作,而且用户可以根据自己的需要对 ...

  5. RocketMQ学习记录

    RocketMQ是一款分布式.队列模型的消息中间件,具有以下特点: 1.能够保证严格的消息顺序 2.提供丰富的消息拉取模式 3.高效的订阅者水平扩展能力 4.实时的消息订阅机制 5.亿级消息堆积能力 ...

  6. Linux下发包处理

    Linux下发包处理: 1.用top分析工具来查看哪个进程占用的CPU资源比较大  2. 通过命令来查看都是那些端口被占用了   netstat -antp | more  3.在top里面查看到的异 ...

  7. 解决Access连接 accdb 不可识别的数据库格式异常

    在Access07之前的数据库后缀名均为*.mdb 而连接字符串写成Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\myFolder\*.mdb ;Pe ...

  8. 怎样用foreach去修改数组之中的数据

    $table_exchange=array(1,2,3,4,5,6,7,8); foreach ($table_exchange as $b=>$c){ $table_exchange[$b]= ...

  9. 一个php函数,能够遍历一个文件夹下的所有文件和子文件夹

    <?phpfunction my_scandir($dir){    $files=array();    if(is_dir($dir))     {        if($handle=op ...

  10. grunt初体验

    最近参与多人团队项目开发过程之中,使用到了grunt来构建项目,包括一些文件的压缩,合并等操作.亲自动手进行grunt任务的配置,学到了很多东西.现将自己的学习过程记录如下: 1.对于一个项目而言,使 ...