Search code examples
c#multithreadinglambdaref

How to pass a ref parameter inside lambda expression? - Thread issue


I have a method to be called.

public void RecordConversation(ref ChannelResource cr)
{
    VoiceResource RecordResource = TServer.GetVoiceResource();
    RecordResource.MaximumTime = 6000;
    RecordResource.MaximumSilence = 6000;
    RecordResource.TerminationDigits = "";
}

To call it in a thread

Thread recordThread = new Thread(() => RecordConversation(ref ChanResource));
recordThread.Start();

Of course we get an error.

Cannot use ref or out parameter 'ChanResource' inside an anonymous method, lambda expression, or query expression

How to fix it?


Solution

  • You can't use ref. See this very same question.

    That being said, the reason you mentioned (The object is big and used often, I don't want to pass it in value type) is not valid.

    You won't pass your parameter as value if you remove ref. There won't be any performance/memory gain to use ref here. See value vs reference.