I have the following code that doesn’t compile. I get the error
Cannot use ref or out parameter ‘messageLockToken’ inside an anonymous method, lambda expression, or query expression
I admit I’m new to Lambdas and am a bit confused about resolving this one. Does anyone know how I can express the logic below in a compiler acceptable manner?
public T Receive<T>(TimeSpan receiveTimeout, out Guid messageLockToken)
{
// do work
}
public Task<T> ReceiveAsync<T>(TimeSpan receiveTimeout, out Guid messageLockToken)
{
Task<T> sendQueueMsgTask = new Task<T>(() => Receive<T>(receiveTimeout, out messageLockToken));
return sendQueueMsgTask;
}
First, your method wouldn’t work even if it compiled. That’s because when you use
new Task(), you always have to callStart()on thatTask(or, alternatively, useTask.Run()).Now, you can’t use the
outparameter here, because it doesn’t make much sense. You want to return theTaskfrom the method immediately, but that also means returning theGuidimmediately. Which means there is no way for your call toReceive()to actually affect the value of theoutparameter.I think using a
Tuple(as Rawling suggested) or a custom return type is the way to go here:This assumes you actually want to do this, see Stephen Toub’s article Should I expose asynchronous wrappers for synchronous methods? for reasons why doing this is probably not a good idea.