Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to use ISynchronizeInvoke without a reference to the Form
    text
    copied!<p>I need to "send" a piece of code from another thread (Excel Interop) to the UI thread to execute. Normally you'd use <code>Invoke</code> on the <code>Form</code>, which implements the <code>ISynchronizeInvoke</code> interface:</p> <pre><code>public class MyForm : Form { ... private void Button_Click(object sender, EventArgs e) { SomeExcelWorkbook.OnBeforeClose += delegate(ref bool Cancel) { this.Invoke(someCode); }; } } </code></pre> <p>Unfortunately there is a layer of abstraction between the form code and the code that defines the event handler, and I don't have a reference to the form at that point:</p> <pre><code>public void CodeExecutedByUIThread() { ISynchronizeInvoke sync; SomeExcelWorkbook.OnBeforeClose += delegate(ref bool Cancel) { sync.Invoke(someCode); }; } </code></pre> <p>When entering <code>CodeExecutedByUIThread</code>, we are still in the UI thread, so in theory everything needed should be there. Unfortunately the <a href="https://stackoverflow.com/questions/3398792/isynchronizeinvoke-in-net/3398808#3398808">Form is the only class implementing that interface</a>, is it?</p> <p><strong>How can I get an <code>ISynchronizeInvoke</code> from within the UI thread?</strong> Apparently <code>Thread.CurrentThread</code> doesn't provide it...</p> <p>Or is there a way to get a <code>SynchronizationContext</code>? How would I retrieve and use that?</p> <p><strong>Update:</strong> Oh, I see, getting the SynchronizationContext object looks as simple as <code>SynchronizationContext.Current</code>, which doesn't need any reference to a form. So I'll google little bit more about how to use that.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload