开发者

An exception when trying to remove an event handler from ThreadPreprocessMessage

开发者 https://www.devze.com 2023-03-03 20:15 出处:网络
Trying to add my event handler to ComponentDispatcher.ThreadPreprocessMessage event like this: using System;

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

精彩评论

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

关注公众号