I have a general question about the usage of invoke. Most of my C# winforms projects have one backgroundworker and obviously a UI. Very soon I realise that I need information from the UI in my backgroundworker or I need to change the UI from my backgroundworker. Example:
//example invoke usage to get information from UI (dateMatch = CheckBox, fromDate&toDate = Datepicker)
bool isDateMatch = false;
dateMatch.Invoke(new MethodInvoker(delegate { isDateMatch = dateMatch.Checked; }));
DateTime fromDt = new DateTime();
fromDate.Invoke(new MethodInvoker(delegate { fromDt = fromDate.Value; }));
DateTime toDt = new DateTime();
toDate.Invoke(new MethodInvoker(delegate { toDt = toDate.Value; }));
//example invoke usage to change UI (statusTxt = TextBox, progressBar = ProgressBar)
private void changeStatus(string statusTextV, bool enableProgressBar)
{
statusTxt.Invoke(new MethodInvoker(delegate { statusTxt.Text = statusTextV; }));
progressBar.Invoke(new MethodInvoker(delegate { progressBar.MarqueeAnimationSpeed = enableProgressBar ? 1 : 0; }));
}
What I mean is that my code is full of invoke methods. Is this something bad and is there a better way to do this.
All of the controls will be on the same UI thread - the same as the form itself, so there is no need to do multiple invokes - and you can use simpler syntax:
private void changeStatus(string statusTextV, bool enableProgressBar) { Invoke((MethodInvoker)delegate { statusTxt.Text = statusTextV; progressBar.MarqueeAnimationSpeed = enableProgressBar ? 1 : 0; }); }