本文介绍了为什么异步委托方法调用需要EndInvoke会?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么需要委托方法火灾前致电EndInvoke会?如果我需要调用EndInvoke会(以阻止该线程),那么它不是一个真正的异步调用呢?

下面是code IM试图运行。

 类节目
    {
        私人委托无效GenerateXmlDelegate();        静态无效的主要(字串[] args)
        {
            GenerateXmlDelegate工人=新GenerateXmlDelegate(GenerateMainXml);
            IAsyncResult的结果= worker.BeginInvoke(NULL,NULL);
        }        私有静态无效GenerateMainXml()
        {
            Thread.sleep代码(10000);
            Console.WriteLine(被代表呼吁GenerateMainXml);
        }
    }


解决方案

您需要调用的原因 EndInvoke会是为了避免内存泄漏; .NET将存储有关函数的结果(或异常)的信息,直到您调用 EndInvoke会

您可以致电 EndInvoke会在您为的BeginInvoke完成处理程序并保留asyncronous性质。

修改

例如:

 类节目{
    私人委托无效GenerateXmlDelegate();    静态无效的主要(字串[] args){
        GenerateXmlDelegate工人=新GenerateXmlDelegate(GenerateMainXml);
        IAsyncResult的结果= worker.BeginInvoke(代表{
            尝试{
                worker.EndInvoke();
            }赶上(...){...}
        }, 空值);
    }    私有静态无效GenerateMainXml(){
        Thread.sleep代码(10000);
        Console.WriteLine(被代表呼吁GenerateMainXml);
    }
}


如果你想火一个异步调用,并忘掉它,你可以使用,像这样的:

  ThreadPool.QueueUserWorkItem(代表{GenerateMainXml();});

Why does the delegate need to call the EndInvoke before the method fires? If i need to call the EndInvoke (which blocks the thread) then its not really an asynchronous call is it?

Here is the code im trying to run.

class Program
    {
        private delegate void GenerateXmlDelegate();

        static void Main(string[] args)
        {
            GenerateXmlDelegate worker = new GenerateXmlDelegate(GenerateMainXml);
            IAsyncResult result = worker.BeginInvoke(null, null);
        }

        private static void GenerateMainXml()
        {
            Thread.Sleep(10000);
            Console.WriteLine("GenerateMainXml Called by delegate");
        }
    }
解决方案

The reason you need to call EndInvoke is to avoid memory leaks; .Net will store information about the function's result (or exception) until you call EndInvoke.

You can call EndInvoke in the completion handler that you give to BeginInvoke and retain the asyncronous nature.

EDIT:

For example:

class Program {
    private delegate void GenerateXmlDelegate();

    static void Main(string[] args) {
        GenerateXmlDelegate worker = new GenerateXmlDelegate(GenerateMainXml);
        IAsyncResult result = worker.BeginInvoke(delegate {
            try {
                worker.EndInvoke();
            } catch(...) { ... }
        }, null);
    }

    private static void GenerateMainXml() {
        Thread.Sleep(10000);
        Console.WriteLine("GenerateMainXml Called by delegate");
    }
}


If you want to fire an async call and forget about it, you can use the ThreadPool, like this:

ThreadPool.QueueUserWorkItem(delegate { GenerateMainXml(); });

这篇关于为什么异步委托方法调用需要EndInvoke会?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 04:05