为什么异步调用不适用于回调模式?

零度

我已按照此Microsoft文档中的异步调用模式进行了演示:http : //support.microsoft.com/kb/315582

在样本5中,有一个示例代码演示了回调模式,但它不起作用。这是示例代码:

using System;
using System.Threading;
using System.Windows.Forms;

namespace Recipe.Ch04
{
    public class AsyncDemo
    {
        string LongRunningMethod (int iCallTime, out int iExecThread)
        {
            Thread.Sleep (iCallTime) ;
            iExecThread = AppDomain.GetCurrentThreadId ();
            return "MyCallTime was " + iCallTime.ToString() ;
        }

        delegate string MethodDelegate(int iCallTime, out int iExecThread)  ;

        public void DemoCallback()
        {
            MethodDelegate dlgt = new MethodDelegate (this.LongRunningMethod) ;
            string s ;
            int iExecThread;

            // Create the callback delegate.
            AsyncCallback cb = new AsyncCallback(MyAsyncCallback);

            // Initiate the Asynchronous call passing in the callback delegate
            // and the delegate object used to initiate the call.
            IAsyncResult ar = dlgt.BeginInvoke(3000, out iExecThread, cb, dlgt); 
        }

        public void MyAsyncCallback(IAsyncResult ar)
        {
            string s ;
            int iExecThread ;

            // Because you passed your original delegate in the asyncState parameter
            // of the Begin call, you can get it back here to complete the call.
            MethodDelegate dlgt = (MethodDelegate) ar.AsyncState;

            // Complete the call.
            s = dlgt.EndInvoke (out iExecThread, ar) ;

            Console.WriteLine (string.Format ("The delegate call returned the string: \"{0}\", and the number {1}", s, iExecThread.ToString() ) );
        }

        static void Main(string[] args)
        {
            AsyncDemo ad = new AsyncDemo () ;
            ad.DemoCallback() ;
        }
    }
}

此回调模式实现有什么问题?为什么它可以编译但在控制台屏幕上不显示任何内容?

在线编译和执行:http : //ideone.com/V8b2NY

斯威克

问题是控制台方法通常在Main()方法返回后立即停止没有什么可以让它等待在后台线程上执行的代码。

最简单的解决方案(但不适用于生产应用程序)是Console.ReadLine()在的末尾添加Main()这样,Main()只有按才返回Enter,因此可以确保应用程序不会过早退出。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章