What Is Asynccallback

What is AsyncCallback?

When the async method finish the processing, AsyncCallback method is automatically called, where post processing statements can be executed. With this technique there is no need to poll or wait for the async thread to complete.

Here's some more explanation on Async Callback usage:

Callback Model: The callback model requires that we specify a method to callback on and include any state that we need in the callback method to complete the call. The callback model can be seen in the following example:

static byte[] buffer = new byte[100];

static void TestCallbackAPM()
{
string filename = System.IO.Path.Combine (System.Environment.CurrentDirectory, "mfc71.pdb");

FileStream strm = new FileStream(filename,
FileMode.Open, FileAccess.Read, FileShare.Read, 1024,
FileOptions.Asynchronous);

// Make the asynchronous call
IAsyncResult result = strm.BeginRead(buffer, 0, buffer.Length,
new AsyncCallback(CompleteRead), strm);
}

In this model, we are creating a new AsyncCallback delegate, specifying a method to call (on another thread) when the operation is complete. Additionally, we are specifying some object that we might need as the state of the call. For this example, we are sending the stream object in because we will need to call EndRead and close the stream.

The method that we create to be called at the end of the call would look something like this:

static void CompleteRead(IAsyncResult result)
{
Console.WriteLine("Read Completed");

FileStream strm = (FileStream) result.AsyncState;

// Finished, so we can call EndRead and it will return without blocking
int numBytes = strm.EndRead(result);

// Don't forget to close the stream
strm.Close();

Console.WriteLine("Read {0} Bytes", numBytes);
Console.WriteLine(BitConverter.ToString(buffer));
}

Other techniques are Wait-until-done and Polling.

Wait-Until-Done Model The wait-until-done model allows you to start the asynchronous call and perform other work. Once the other work is done, you can attempt to end the call and it will block until the asynchronous call is complete.

// Make the asynchronous call
strm.Read(buffer, 0, buffer.Length);
IAsyncResult result = strm.BeginRead(buffer, 0, buffer.Length, null, null);

// Do some work here while you wait

// Calling EndRead will block until the Async work is complete
int numBytes = strm.EndRead(result);

Or you can use wait handles.

result.AsyncWaitHandle.WaitOne();

Polling Model The polling method is similar, with the exception that the code will poll the IAsyncResult to see whether it has completed.

// Make the asynchronous call
IAsyncResult result = strm.BeginRead(buffer, 0, buffer.Length, null, null);

// Poll testing to see if complete
while (!result.IsCompleted)
{
// Do more work here if the call isn't complete
Thread.Sleep(100);
}

Confused how AsyncCallback works

I am almost 100% sure you have completely bastardized the naming convention using in sampleFunction1 and sampleFunction2

I am sure you meant.

public class Foo
{
public void BeginSampleFunction(AsyncCallback callback, object x)
{
//download some content as a string
}

public string EndSampleFunction(IAsyncResult result)
{
//download some content as a string
}
}

The test code should be

public void Test()
{
AsyncCallback callback = a =>
{
string result = foo.EndSampleFunction(a);
Console.WriteLine(result);
}
object state = null;
foo.BeginSampleFunction(callback, state);
}

This pattern is called the Asynchronous Programming Model (APM). It is completely deprecated, and should not be used. Today we use Task Asynchronous Programming (TAP).

In TPL there is a factory method for converting methods from APM to TAP.

public async Task Test()
{
Task<string> task = Task.Factory.FromAsync(foo.BeginSampleFunction, foo.EndSampleFunction, null);
string result = await task;
Console.WriteLine(result);
}

What is AsyncCallBack in Android?

There is no class named AsyncCallback in android. I think what you are looking for is AsyncTask which is a way to run a piece of code on another Thread so the UI won't be blocked, and receive it's results on the UI thread. For example, say you want to talk to a server on the internet in response to the user clicking something in the UI, then receive some result from the server, and update the UI. AsyncTask makes doing this very easy compared to doing regular threading code because threading lifecycle and communication back to the UI thread is handled for you. As a bonus there is also support for canceling a background task, but you have to write the code to handle it when cancel is called. It doesn't do it without some work on your side.

What is the purpose of `AsyncCallback` and `@object` in regards to delegates in .Net

AsyncCallback is a delegate type that acts as a callback function.

If you pass a function as this parameter, .Net will call your callback after the delegate finishes executing asynchronously.

The second parameter allows you to pass state to the AsyncCallback so that your callback function can know what it's coming from.

What're AsyncCallback and AsyncState for in Async WCF`?

There are a couple of design patterns in .NET for exposing asynchronous methods.

This pattern with BeginX and EndX methods is called the Asynchronous Programming Model

In this pattern, you can always pass these two extra parameters:

1) AsyncCallback callback is a delegate which is called when the operation completes.

2) object state is any object you want to associate with the request.

The caller can provide these two parameters, or leave them null, depending on the use case.

See MSDN: Asynchronous Programming Model (APM)


ADDENDUM:

In the case of an async WCF service implementation, WCF itself is the "client" and populates the two extra parameters.

Here's the workflow:

1) request comes from client.


2) WCF constructs an AsyncCallback and a state object


3) WCF calls your BeginX method and passes the parameters


4) In your method, you construct an IAsyncResult object using WCF's parameters


5) You initiate some background work and return your IAsyncResult object


6) WCF waits for its AsyncCallback to be called


7) WCF calls your EndX method and returns the response to the web service client.

The client doesn't know anything about this and may call this web service using either client-side synchronous or asynchronous calls.

Does C# AsyncCallback creates a new thread?

It is entirely an implementation detail of the class' BeginXxx() method. There are two basic schemes:

  • BeginXxx() starts a thread to get the job done, that thread makes the callback
  • BeginXxx() asks the operating system to get job done, using an I/O completion port to ask to be notified when it is done. The OS starts a thread to deliver the notification, that runs the callback.

The second approach is very desirable, it scales well with the program being able to have many pending operations. And is the approach used by HttpListener, the TCP/IP driver stack on Windows supports completion ports. Your program can support thousands of sockets easily, important in server scenarios.

The EndXxx() call in the callback reports any mishaps encountered while trying to complete the I/O request by throwing an exception. In your case, the BeginGetContext() requires EndGetContext() in the callback. If you don't catch the exception then your program will terminate.

Your code snippet does not actually demonstrate any asynchronous I/O. You called GetResponse() instead of BeginGetResponse(). No callback is involved at all, it will thus be the GetResponse() method that fails and throws the exception.

What is the difference between Asynchronous calls and Callbacks

Very simply, a callback needn't be asynchronous.

http://docs.apigee.com/api-baas/asynchronous-vs-synchronous-calls

  1. Synchronous:

    If an API call is synchronous, it means that code execution will
    block (or wait) for the API call to return before continuing. This
    means that until a response is returned by the API, your application
    will not execute any further, which could be perceived by the user as
    latency or performance lag in your app. Making an API call
    synchronously can be beneficial, however, if there if code in your app
    that will only execute properly once the API response is received.

  2. Asynchronous:

    Asynchronous calls do not block (or wait) for the API call to return
    from the server. Execution continues on in your program, and when the
    call returns from the server, a "callback" function is executed.

In Java, C and C#, "callbacks" are usually synchronous (with respect to a "main event loop").

In Javascript, on the other hand, callbacks are usually asynchronous - you pass a function that will be invoked ... but other events will continue to be processed until the callback is invoked.

If you don't care what Javascript events occur in which order - great. Otherwise, one very powerful mechanism for managing asynchronous behavior in Javascript is to use "promises":

http://www.html5rocks.com/en/tutorials/es6/promises/

PS:
To answer your additional questions:

  1. Yes, a callback may be a lambda - but it's not a requirement.

    In Javascript, just about every callback will be an "anonymous function" (basically a "lambda expression").

  2. Yes, callbacks may be invoked from a different thread - but it's certainly not a requirement.

  3. Callbacks may also (and often do) spawn a thread (thus making themselves "asynchronous").

'Hope that helps

====================================================================

Hi, Again:

Q: @paulsm4 can you please elaborate with an example how the callback
and asynchronous call works in the execution flow? That will be
greatly helpful

  1. First we need to agree on a definition for "callback". Here's a good one:

    https://en.wikipedia.org/wiki/Callback_%28computer_programming%29

    In computer programming, a callback is a piece of executable code that
    is passed as an argument to other code, which is expected to call back
    (execute) the argument at some convenient time. The invocation may be
    immediate as in a synchronous callback, or it might happen at a later
    time as in an asynchronous callback.

  2. We must also define "synchronous" and "asynchronous". Basically - if a callback does all it's work before returning to the caller, it's "synchronous". If it can return to the caller immediately after it's invoked - and the caller and the callback can work in parallel - then it's "asynchronous".

  3. The problem with synchronous callbacks is they can appear to "hang". The problem with asynchronous callbacks is you can lose control of "ordering" - you can't necessarily guarantee that "A" will occur before "B".

  4. Common examples of callbacks include:

    a) a button press handler (each different "button" will have a different "response"). These are usually invoked "asynchronousy" (by the GUI's main event loop).

    b) a sort "compare" function (so a common "sort()" function can handle different data types). These are usually invoked "synchronously" (called directly by your program).

  5. A CONCRETE EXAMPLE:

    a) I have a "C" language program with a "print()" function.

    b) "print()" is designed to use one of three callbacks: "PrintHP()", "PrintCanon()" and "PrintPDF()".

    c) "PrintPDF()" calls a library to render my data in PDF. It's synchronous - the program doesn't return back from "print()" until the .pdf rendering is complete. It usually goes pretty quickly, so there's no problem.

    d) I've coded "PrintHP()" and "PrintCanon()" to spawn threads to do the I/O to the physical printer. "Print()" exits as soon as the thread is created; the actual "printing" goes on in parallel with program execution. These two callbacks are "asynchronous".

Q: Make sense? Does that help?

How to call AsyncCallback with a parameter in an BeginGetRequestStream (C#)

Use a lambda instead of a method group.

That is:

webRequest.BeginGetRequestStream(new AsyncCallback(result => GetRequestStreamCallback(result, someParameter)), webRequest);

Thread data sync when use AsyncCallback

I have do some test to find out:

  1. pure async function call will not do thread sync for user.

    public class main
    {
    struct SharedData
    {
    public int a;
    public int b;
    }
    static SharedData d = new SharedData();
    public void TestMethod()
    {
    if (d.a != d.b)
    Console.WriteLine(d.a+" " +d.b);
    }
    public void callback(System.IAsyncResult ar)
    {
    d.a -= 1;
    d.b -= 1;
    }
    static AsyncMethodCaller caller;
    static void Main(string[] args)
    {
    d.a = 99999999;
    d.b = 99999999;
    main a = new main();
    caller = new AsyncMethodCaller(a.TestMethod);
    while (true)
    caller.BeginInvoke(new System.AsyncCallback(a.callback), null);
    }
    public delegate void AsyncMethodCaller();
    }

In this example, shared object d soon will corrupted.


  1. Above thing will not happen in Socket class async operations. I use same test way in Socket class BeginReceive and callback function, the sending data frequency is 1 millisecond, data payload is 0~10 number of int32. I run about 1 hour, no corruption happen. This should be the MSDN doc said Socket class is thread safety meaning. However, generally, thread safe class means this class's methods can be concurrent. But the point is will class's method concurrent with the callback function(not class's method)? Through my test, the answer is yes.

  2. Access shared data by IAsyncResult can have the effect of thread sync

    public class main
    {
    struct SharedData
    {
    public int a;
    public int b;
    }
    static SharedData d = new SharedData();
    public void TestMethod()
    {
    if (d.a != d.b)
    Console.WriteLine(d.a+" " +d.b);
    }
    public void callback(System.IAsyncResult ar)
    {
    SharedData dd = (SharedData)ar.AsyncState;
    dd.a -= 1;
    dd.b -= 1;
    }
    static AsyncMethodCaller caller;
    static void Main(string[] args)
    {
    d.a = 99999999;
    d.b = 99999999;
    main a = new main();
    caller = new AsyncMethodCaller(a.TestMethod);
    while (true)
    caller.BeginInvoke(new System.AsyncCallback(a.callback), d);
    }
    public delegate void AsyncMethodCaller();
    }

    Unlike example 1, the corruption will not happen.



Related Topics



Leave a reply



Submit