title: using PInvoke in WPF with ui/non-ui thread difference
body: <p>I access a c++ dll library from c# code in a WPF application. I have no problems while accessing the dll from the ui thread. But I need the UI to be responsive while the code of the c++ dll is running. So I try to access it from another thread. But when I try to call the same function (that I call from the ui thread) in a non-ui thread <strong>for the first time</strong>, the function returns but the return value indicates there is an internal error in the function. But when I run the code from a non-ui thread <strong>once or twice more</strong>, it successfully returns a non-error value. I don't have the source code of the dll so I am not sure what happens inside.</p>
  
  <p>c++ function</p>
  
  <pre><code>UINT32 myfunc1()
  </code></pre>
  
  <p>In C#</p>
  
  <pre><code>[DllImport("mydll.dll")]
  public static extern uint myfunc1();
  </code></pre>
  
  <p>How I reach the code in ui thread</p>
  
  <pre><code>uint errorCode = myfunc1(); // returns 0 means no error occured
  </code></pre>
  
  <p>How I reach the code in non-ui thread</p>
  
  <pre><code>BackgroundWorker worker = new BackgroundWorker();
  worker.DoWork += (s, args) =&gt; { args.Result = myfunc1(); };
  // 1st call args.Result is 10 means internal error ocurred
  // 2nd call args.Result is sometimes 0 and sometimes 10
  // 3rd or later calls args.Result is 0 means no error occured
  worker.RunWorkerCompleted += doSth();
  worker.RunWorkerAsync();
  </code></pre>