When passing a variable using the ref keyword, you cannot use it inside a lambda expression. Try using a local variable inside lambda and assign the ref variable outside of it, if possible (somewhat simplified example):
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(() => { temp = 3;
Update
In response to the updated answer: your problem is that the _dataSet inside the lambda expression is not the same variable as the dataSet outside the lambda expression. You can do the following:
class DataSetContainer { public DataSet DataSet { get; set; } }
Now we have a reference type with a property that can be safely changed inside the lambda expression:
public static void Select(DataGridView dataGridView, DataSetContainer dataSetContainer, params object[] parameters) { AsyncCommandExecutor commandExecutor = new AsyncCommandExecutor(System.Threading.SynchronizationContext.Current); commandExecutor.ExecuteWithContinuation( () => {
}
In the above code, the lambda expression will update the DataSet property of the DataSetContainer instance passed to the Select method. Since you are not changing the passed argument itself, but only a member of this instance, there is no need for the ref keyword, and we also bypass the closure problem.
Update 2
And now that I have turned on my brain, I understand that the Select method makes an asynchronous call. It is very likely that the code looks like the last line is the Select method, which will be executed long before _dataSet , and as a result it will be null . To get around this, you probably want to examine some kind of signaling mechanism (e.g. ManualResetEvent or AutoResetEvent ) to know when the assignment is being executed.
source share