开发者

C# /ASP.NET Asynchronous Thread Execution

开发者 https://www.devze.com 2022-12-12 10:29 出处:网络
I have some doubts on executing the following : public class Test { delegate int TestDelegate(string parameter);

I have some doubts on executing the following :

public class Test
{
    delegate int TestDelegate(string parameter);

    static void Main()
    {
        TestDelegate d = new TestDelegate(PrintOut);

        d.BeginInvoke("Hello", new AsyncCallback(Callback), d);

        // Give the callback time to execute - otherwise the app
        // may terminate before it is called
        Thread.Sleep(1000开发者_如何转开发);
        Console.ReadKey(true);
    }

    static int PrintOut(string parameter)
    {
        Console.WriteLine(parameter);
        return 5;
    }

    static void Callback(IAsyncResult ar)
    {
        TestDelegate d = (TestDelegate)ar.AsyncState;
        Console.WriteLine("Delegate returned {0}", d.EndInvoke(ar));
    }
}

1 ) The TestDelegate already pointing to a Method ( "PrintOut").Why do Again we are passing another method ("callback") in d.BeginInvoke("Hello",new AysncCallback(Callback),d);.Does it mean d.BeginInvoke executes "PrintOut" and "Callback" parallely?.Can you please explain line by line what exactly going on?

2) Normally, Aysnchronous execution means the execution of a "thread" is not predictable or fastest execution ?

3) TestDelegate d = (TestDelegate)ar.AsyncState; "TestDelegate" d is a delegate.How is it possible to cast it to filed or property? ( ar.AsyncState )

4) can you provide me some live example where do i need to use this Asynchronous execution?


1 ) The TestDelegate already pointing to a Method ( "PrintOut").Why do Again we are passing another method ("callback") in d.BeginInvoke("Hello",new AysncCallback(Callback),d);.Does it mean d.BeginInvoke executes "PrintOut" and "Callback" parallely?.Can you please explain line by line what exactly going on?

  • PrintOut and Callback are not executed in paralled. Callback will be called when PrintOut has finished and returned.

2) Normally, Aysnchronous execution means the execution of a "thread" is not predictable or fastest execution ?

  • No. Asynchronous execution means the execution is not synchronous. That is.. the timing and execution time of the execution are not related to the timing of the piece of code that starts the asynchronous operation. It is the opposite of synchronous execution. With synchronous operation you would expect the execution to complete before the next statement is executed. For example, calling another method directly is synchronous operation, or another example is calling a function on a remote service and waiting for it to return before continuing.

3) TestDelegate d = (TestDelegate)ar.AsyncState; "TestDelegate" d is a delegate.How is it possible to cast it to filed or property? ( ar.AsyncState )

  • The delegate is not being case to a field or property. The cast is the other way around. The field or property is being cast into a TestDelegate.

4) can you provide me some live example where do i need to use this Asynchronous execution?

  • An example might be if you have a user interface that displays reports. The report might need to be generated from data in a database and takes a long time to generate. You would want to generate the report asynchronously so that the user interface can carry on running. If the report was not generated asynchronously the user interface might appear to be frozen and the user might think the program has crashed.


PrintOut is the function that will be executed on a thread from the thread pool and is the function your delegate is pointing to. Callback is the function that will be executed once PrintOut finishes and in which you have to call the EndXXX method which will give you the result of the PrintOut execution. These two functions are not executed in parallel. Here's line by line:

  1. Create a delegate pointing to the PrintOut method
  2. Draw a thread from the thread pool (if available) and run the PrintOut method on this thread by passing "Hello" as argument.
  3. In the meantime the main thread sleeps for 1 second
  4. Once the PrintOut method finishes executing, the Callback method is called. This is where you handle the result of the asynchronous operation.

As far as the casting is concerned: AsyncState is an object, a delegate in .NET is also an object, so no problem casting.


1) Callback will be called by the runtime after PrintOut is executed.

2) Yes, it is not predictable. BeginInvoke makes code to execute on thread from pool, so real performance depends on many parameters, such as thread usage in other places of your program.

3) Delegates are objects. So, reference to them can be casted to object and backward. In case of IAsyncResult returned by BeginInvoke, AsyncState stores delegate, to make proper result extraction possbile.

4) A fragment from a program opening turnstile and making indication (both are time consuming) after user authentication:

if(user.Id.HasValue)
{
    Action openDoor = turnstile.Open;
    Action<LedColor> indicate = led.SetColor;
    // starting async operations
    openDoor.BeginInvoke(openDoor.EndInvoke, null);
    indicate.BeginInvoke(LedColor.Green, indicate.EndInvoke, null);
    // main thread activity.
    MakeRecordToLog();
}


1) The callback gets called after your work (PrintOut) has finished. You can pass also a null value.

2) Aysnchronous execution means that your code runs on another thread than the main thread of the application.

3) ar.AsyncState is set to the value you passed in the 3rd parameter of the BeginInvoke method.

4) Check out this: http://shiman.wordpress.com/2008/09/10/c-net-delegates-asynchronous-invocation-begininvoke-method/

0

精彩评论

暂无评论...
验证码 换一张
取 消