title: How to cleanly stop a .NET thread that is running a matlab dll function
body: <p>I compiled a Matlab DLL with namespace flagTest and class name test with this function:</p>
  
  <pre><code>function [ ] = flagTest( flag )
      while flag
          disp(flag);
          pause(1);
      end
  end
  </code></pre>
  
  <p>I can call this dll function in c# like this:</p>
  
  <pre><code>using MathWorks.MATLAB.NET.Arrays;
  using MathWorks.MATLAB.NET.Utility;
  namespace ConsoleApplication1
  {
      class Program
      {
          static void Main(string[] args)
          {
              //create test class object
              flagTest.test T = new flagTest.test();
              MWLogicalArray flag = new MWLogicalArray(true);
              //call matlab function flagTest
              T.flagTest(flag);
          }
      }
  }
  </code></pre>
  
  <p>I am sorry if it causes any confusion since I call both my namespace and function <code>flagTest</code>.</p>
  
  <p>What I want to do now is to put this <code>T.flagTest(flag)</code> function call on a thread  (which I know how to do), and change the value of <code>flag</code> to <code>false</code> as user click a button on the UI to stop the thread. In the real matlab function in our application, I will need to do quite some work such as finish reading the current file and write the data in memory to disk before I can stop the function thread. I cannot just stop the thread without doing anything in the matlab function.</p>
  
  <p>I am wondering if there's anyway to achieve this functionality as I was not able to figure out how to pass an object by reference from .NET to Matlab.</p>