简体   繁体   English

C#/ASP.NET异步线程执行

[英]C# /ASP.NET Asynchronous Thread Execution

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? 1)TestDelegate已经指向一个方法( “ PrintOut” )。为什么我们再次在d.BeginInvoke(“ Hello”,new AysncCallback(Callback) ,d);中传递另一个方法(“ 回调 ”)? d.BeginInvoke并行执行“ PrintOut”和“ Callback”吗?您能逐行解释到底发生了什么吗?

2) Normally, Aysnchronous execution means the execution of a "thread" is not predictable or fastest execution ? 2)通常,异步执行是指“线程”的执行是不可预测的还是最快的执行?

3) TestDelegate d = (TestDelegate)ar.AsyncState; 3) TestDelegate d = (TestDelegate)ar.AsyncState; "TestDelegate" d is a delegate.How is it possible to cast it to filed or property? “ TestDelegate” d是一个委托。如何将其强制转换为文件或属性? ( ar.AsyncState ) ar.AsyncState

4) can you provide me some live example where do i need to use this Asynchronous execution? 4)您能否提供一些实时示例,我需要在哪里使用此异步执行?

PrintOut is the function that will be executed on a thread from the thread pool and is the function your delegate is pointing to. PrintOut是将在线程池中的线程上执行的函数,也是您的委托指向的函数。 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. Callback是将在PrintOut完成后执行的函数,您必须在其中调用EndXXX方法,该方法将为您提供PrintOut执行的结果。 These two functions are not executed in parallel. 这两个功能不能并行执行。 Here's line by line: 这是一行一行:

  1. Create a delegate pointing to the PrintOut method 创建一个指向PrintOut方法的委托
  2. Draw a thread from the thread pool (if available) and run the PrintOut method on this thread by passing "Hello" as argument. 从线程池中绘制线程(如果可用),并通过传递“ Hello”作为参数在此线程上运行PrintOut方法。
  3. In the meantime the main thread sleeps for 1 second 同时,主线程休眠1秒
  4. Once the PrintOut method finishes executing, the Callback method is called. 一旦PrintOut方法完成执行,就会调用Callback方法。 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. 就转换而言: AsyncState是一个对象,.NET中的委托也是一个对象,因此转换没有问题。

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? 1)TestDelegate已经指向一个方法(“ PrintOut”)。为什么要再次在d.BeginInvoke(“ Hello”,new AysncCallback(Callback),d);中传递另一个方法(“ callback”)? d.BeginInvoke并行执行“ PrintOut”和“ Callback”吗?您能逐行解释到底发生了什么吗?

  • PrintOut and Callback are not executed in paralled. PrintOut和Callback不会并行执行。 Callback will be called when PrintOut has finished and returned. 当PrintOut完成并返回时,将调用回调。

2) Normally, Aysnchronous execution means the execution of a "thread" is not predictable or fastest execution ? 2)通常,异步执行是指“线程”的执行是不可预测的还是最快的执行?

  • 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; 3)TestDelegate d =(TestDelegate)ar.AsyncState; "TestDelegate" d is a delegate.How is it possible to cast it to filed or property? “ TestDelegate” d是一个委托。如何将其强制转换为文件或属性? ( ar.AsyncState ) (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. 该字段或属性将被强制转换为TestDelegate。

4) can you provide me some live example where do i need to use this Asynchronous execution? 4)您能否提供一些实时示例,我需要在哪里使用此异步执行?

  • 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. 如果未异步生成报告,则用户界面可能似乎被冻结,并且用户可能认为程序已崩溃。

1) Callback will be called by the runtime after PrintOut is executed. 1)执行PrintOut后,运行时将调用Callback

2) Yes, it is not predictable. 2)是的,这是不可预测的。 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. BeginInvoke使代码在池中的线​​程上执行,因此实际性能取决于许多参数,例如程序其他位置的线程使用情况。

3) Delegates are objects. 3)代表是对象。 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. 如果BeginInvoke返回IAsyncResult ,则AsyncState将存储委托,以使适当的结果提取成为可能。

4) A fragment from a program opening turnstile and making indication (both are time consuming) after user authentication: 4)用户身份验证后,程序打开旋转门并做出指示(均为耗时)的片段:

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. 1)您的工作(PrintOut)完成后,将调用回调。 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. 2)异步执行意味着您的代码在应用程序主线程以外的其他线程上运行。

3) ar.AsyncState is set to the value you passed in the 3rd parameter of the BeginInvoke method. 3)ar.AsyncState设置为您在BeginInvoke方法的第3个参数中传递的值。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM