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

问题描述

为什么委托需要在方法触发之前调用 EndInvoke?如果我需要调用 EndInvoke(它会阻塞线程),那么它并不是真正的异步调用,是吗?

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");
        }
    }

推荐答案

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

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.

您可以在提供给 BeginInvoke 的完成处理程序中调用 EndInvoke 并保留异步性质.

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

编辑:

例如:

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");
    }
}

如果您想触发异步调用并忘记它,您可以使用 ThreadPool,像这样:

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

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

05-16 01:54