开发者

An exception when trying to remove an event handler from ThreadPreprocessMessage

Trying to add my event handler to ComponentDispatcher.ThreadPreprocessMessage event like this:

using System;
using System.Windows.Interop;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            new Cc();
        }
    }

    public class Cc
    {
        public Cc()
        {
            ComponentDispatcher.ThreadPreprocessMessage += Method;
        }

        ~Cc()
        {
            ComponentDispatcher.ThreadPreprocessMess开发者_JAVA百科age -= Method;
        }

        private void Method(ref MSG msg, ref bool handled)
        {
        }
    }
}

And when I run it, I get this exception in the destructor:

Unhandled Exception: System.InvalidOperationException: LocalDataStoreSlot storage has been freed.

What causes it and how can I fix it?


As the docs state. The register and unregister calls are stored in a thread local data structure. You just did try to unregister in a finalizer which is run on the finalizer thread (== Different Thread). This will not work since you must unregister on the same thread where you did register.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜