Skip to content

Instantly share code, notes, and snippets.

@DamianSuess
Created October 10, 2017 16:35
Show Gist options
  • Save DamianSuess/786816717b2d607cfc9cfa84a703e8d9 to your computer and use it in GitHub Desktop.
Save DamianSuess/786816717b2d607cfc9cfa84a703e8d9 to your computer and use it in GitHub Desktop.
GUI Thread-Safe Updates
namespace XenoInc.Gist
{
public static class Test
{
/// <summary>
/// Execute on UI thread asynchronously (don't wait for completion)
/// </summary>
/// <param name="control"></param>
/// <param name="code"></param>
/// <example>
/// Store.ExecuteThread(this, () =>
/// {
/// Text1.Text = "Something new";
/// });
/// </example>
public static void ExecuteThread(this Control control, Action code)
{
if (control.InvokeRequired)
{
control.BeginInvoke(code);
return;
}
code.Invoke();
}
/// <summary>
/// Execute on UI thread synchronously (waiting for completion before continuing).
/// Use this if we're reading back data from GUI thread, like text or something.
/// </summary>
/// <param name="control"></param>
/// <param name="code"></param>
/// <example>
/// Store.ExecuteThread(this, () =>
/// {
/// string getText = Text1.Text;
/// });
/// </example>
public static void ExecuteThreadInvoke(this Control control, Action code)
{
if (control.InvokeRequired)
{
control.Invoke(code);
return;
}
code.Invoke();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment