title: Keeping PInvoked method alive
body: <p>Here's my C code:</p>
  
  <pre><code>    LIBRARY_API bool __cdecl Initialize(void (*FirstScanForDevicesDoneFunc)(void));
  </code></pre>
  
  <p>And here's C# PINvoke code to work with this DLL:</p>
  
  <pre><code>    [UnmanagedFunctionPointer(CallingConvention.Cdecl)]
      public delegate void FirstScanForDevicesDoneFunc();
  
      [DllImport("Native.dll", CallingConvention=CallingConvention.Cdecl)]
      public static extern bool Initialize(FirstScanForDevicesDoneFunc);
  </code></pre>
  
  <p>When I call this method like this:</p>
  
  <pre><code>    static public void Init() {
          Initialize(FirstScanForDevicesDone);
      }
  
      static public void FirstScanForDevicesDone() {
          //do something
      }
  </code></pre>
  
  <p>At the end of <em>Init()</em> when callback comes I get <em>NullReferenceException</em>. So I use Thread to keep it and everything works fine, but I'm not happy with this solution:</p>
  
  <pre><code>    static public bool Working = true;
  
      static public void Init() {
          new Thread(() =&gt;
          {
              Thread.CurrentThread.IsBackground = true;
  
              Initialize(FirstScanForDevicesDone);
              while (Working)
              {
                  Thread.Sleep(1000);
              }
          }).Start();
      }
  </code></pre>
  
  <p>Is there a more sophisticated way to keep this working?</p>