title: Calling a delegate in C# dll
body: <p>I'm working, for the first time, on a C# DLL. The DLL methods will be called by a C# application. The UI will be in the C# application. Up to now it's pretty basic.</p>
  
  <p>But the work in the DLL has to be done in a thread belonging to the DLL. The work in the DLL can’t be executed in the UI thread context. So the DLL methods calls will be asynchronous and that's fine.</p>
  
  <p>So basically the idea would be:</p>
  
  <ul>
  <li>The application includes the DLL in its project.</li>
  <li>The DLL defines various delegates.</li>
  <li>The application "subscribes" to these delegates.</li>
  <li>The UI thread calls a DLL method.</li>
  <li>The DLL receives the method call.</li>
  <li>There is a context switch to the DLL thread (to actually do the work associated with the method call).</li>
  <li>The UI thread continues its execution. The UI thread is not blocked and it doesn't wait.</li>
  <li>The DLL thread does some work.</li>
  <li>The DLL thread calls a delegate to notify the UI thread of the result.</li>
  </ul>
  
  <p>How should the UI thread post a message to the DLL thread? Is there a straightforward way to do this?</p>
  
  <p>What happens when the DLL thread calls the delegate? Is the delegate code executed in the DLL thread context or in the UI thread context?</p>
  
  <p>It seems like the code will be executed in the DLL thread context. If it is the case, how can the delegate code be executed in the UI thread context?</p>
  
  <p>Thanks for the help!</p>
  
  <p>==================</p>
  
  <p>EDIT: The DDL thread must stay alive as long as the application is alive. The DLL thread will also receive events from the network and then notify the UI thread.</p>
  
  <p>In fact, the DLL needs to be a SDK to make VOIP calls. So anyone ready to code the UI could use our SDK.</p>
  
  <p>A typical (simplified) scenario would be:</p>
  
  <ul>
  <li><p>At the application starts, the UI calls the DLL.Start(). This creates a thread within the DLL and make sure the DLL is ready to make and receive calls.</p></li>
  <li><p>The user dials a telephone number.</p></li>
  <li><p>The UI thread calls the MakeCall() method from the DLL.</p></li>
  <li><p>In the DLL, there is context switch to the DLL thread in order to start the new call. All the work for starting the call is made in the DLL thread.</p></li>
  <li><p>The UI thread is not blocked or doesn’t wait.</p></li>
  <li><p>At one point, the call is established.</p></li>
  <li><p>The DLL thread notifies the UI by calling a delegate method.</p></li>
  </ul>