Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>When passing the variable using the <code>ref</code> keyword, you can't use it inside a lambda expression. Try using a local variable inside the lambda and assign the <code>ref</code> variable outside it, if possible (somewhat simplified example):</p> <pre><code>private static void Main(string[] args) { int i = 0; DoSomethingThatTakesAgesAndNeedsToUpdateUiWhenFinished(ref i); Console.WriteLine(i); } public static void DoSomethingThatTakesAgesAndNeedsToUpdateUiWhenFinished(ref int i) { int temp = i; Thread t = new Thread(() =&gt; { temp = 3; // assign the captured, local variable }); t.Start(); t.Join(); i = temp; // assign the ref parameter } </code></pre> <p><strong>Update</strong><br> In response to the updated answer: your problem is that <code>_dataSet</code> inside the lambda expression is not the same variable as dataSet outside the lambda expression. What you could do is the following:</p> <pre><code>class DataSetContainer { public DataSet DataSet { get; set; } } </code></pre> <p>Now we have a reference type with a property that we can safely modify inside the lambda expression:</p> <pre><code>public static void Select(DataGridView dataGridView, DataSetContainer dataSetContainer, params object[] parameters) { AsyncCommandExecutor commandExecutor = new AsyncCommandExecutor(System.Threading.SynchronizationContext.Current); commandExecutor.ExecuteWithContinuation( () =&gt; { // this is the long-running bit dataSetContainer.DataSet = getDataFromDb(parameters); // This is the continuation that will be run on the UI thread return () =&gt; { dataGridView.DataSource = _dataSet.Tables[0].DefaultView; }; }); } </code></pre> <p>}</p> <p>In the above code, the lambda expression will update the <code>DataSet</code> property of the <code>DataSetContainer</code> instance that is passed to the <code>Select</code> method. Since you are not modifying the passed argument itself but only a member of that instance there is no need for the <code>ref</code> keyword, and we also get around the closure issue. </p> <p><strong>Update 2</strong><br> And now when I switched on my brain, I realize that the <code>Select</code> method makes an asynchronous call. It is quite likely as the code looks that the last line is the <code>Select</code> method will be executed long before <code>_dataSet</code> is being assigned, and as a result it will be <code>null</code>. To get around this you probably want to look into using some sort of signaling mechanism (such as <code>ManualResetEvent</code> or <code>AutoResetEvent</code>) to know when the assignment is done.</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