Note that there are some explanatory texts on larger screens.

plurals
  1. POthis.Invoke(...) - is this bad practice?
    text
    copied!<p>I have a function called ExecuteCommand that does things based on a user's input. These things can range from simply doing a Console.Writeline(), checking a check box on my form, or simulating keystrokes to another process, completely independent from my own. The function runs on a separate thread, so changing the UI will requiring some invoking. I have 2 ways of doing it... one of which I'm not sure is a good way but it's very easy.</p> <p>Code below, the 3rd line is what I have a question with:</p> <pre><code>private void ExecuteCommand() { this.Invoke((MethodInvoker)delegate() { if (current_line_index &lt; command_que.Count) { current_line = command_que[current_line_index]; if (current_line.StartsWith("&gt;&gt;Auto Enter")) { chkAutoEnter.Checked = false; } else if (current_line.StartsWith("+WinWait(")) { string title_to_wait_for = current_line; title_to_wait_for = title_to_wait_for.Remove(0, "+WinWait(\"".Length); title_to_wait_for = title_to_wait_for.Remove(title_to_wait_for.Length - 2, 2); t_WinWait = new Thread(() =&gt; WinWait(title_to_wait_for)); t_WinWait.Name = "WinWait"; t_WinWait.Start(); } } }); } </code></pre> <p>The code works perfectly... but I am not sure if it's good practice. </p> <p>Alternativly, I know I can do something like this to change the UI:</p> <pre><code>private delegate void CheckCheckBoxHandler(bool checked); private void CheckCheckBox(bool checked) { if (this.chkAutoEnter.InvokeRequired) { this.chkAutoEnter.Invoke(new CheckCheckBoxHandler(this.CheckCheckBox), checked); } else { chkAutoEnter.Checked = checked; } } </code></pre> <p>But as I have multiple controls on my form that will be changed from another thread, I'd have to add a bunch of functions to do that, versus the simple method in the first example.</p> <p>Is the first way bad in anyway? Are there any risks involved I haven't come across yet? It seems to good to be true...</p> <p>Thanks!</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload