This relates to my previous post here, where I asked why I should use SynchronizationContext's .Send or .Post, over just a regular .Invoke or .BeginInvoke on my main UI Form.
My issue is that the delegate I used to use with Invoke is associated with a method that takes two parameters: one string that holds the actual text the label should be changed to, and another string that holds the name of the label whose text should change.
The issue now is that .Send and .Post only takes the SendOrPostCallbake delegate as its input, and that delegate can only be associated with methods that have a single object as its parameter. As everything can be packed into an object, I was advised to either create a class to pack my variables in (that option I understand how to implement), and the other was to use lambda expressions with closures. It is the latter that I do not understand how to do.
Any guidance on how to use lambda expressions in _synch.Send() when my underlying method has two string parameters, would be greatly appreciated.
EDIT. Based on guidance in comments I was able to answer my own question. I have posted the solution below for the benefit of future visitors.
Based on guidance provided in comments, I have written the below solution.
In main UI class:
public SynchronizationContext UISynchContext { get; private set; }
public static MainForm Get { get; private set; }
public MainForm()
{
InitializeComponent();
Get = this;
UISynchContext = SynchronizationContext.Current;
}
public void UpdateText(string labelName, string text)
{
var label = (Label)Controls.Find(labelName, true).FirstOrDefault();
if (label != null) label.Text = text;
}
In worker class:
private readonly SynchronizationContext _uiSynch;
public Worker(UpdateValueCallback updateValueCallback, Player player)
{
_uiSynch = MainForm.Get.UISynchContext;
}
_uiSynch.Send(o =>
{
string labelName = "lbOne";
string labelText = methodThatReturnsNewText();
MainForm.Get.UpdateText(labelName, labelText);
}, null);