BeginInvoke(new ThreadStart(() => toolStripButton1.Text = "aaa"));
1、非跨线程操作和部分跨线程get不会引发异常;
2、跨线程set,见上面的例子。
3、部分跨线程get,见下面的例子。
var a = (int)EndInvoke(BeginInvoke(new Func<int>(() => toolStripComboBox1.SelectedIndex)));
public static class UIInvokeHelper
{
public static void InvokeUI(this Form form, Action action)
{
if (form == null)
{
throw new ArgumentNullException("form");
}
if (action == null)
{
throw new ArgumentNullException("action");
}
if (form.InvokeRequired)
{
form.Invoke(new Action(action), null);
}
else
{
action();
}
}
public static T InvokeUI<T>(this Form form, Func<T> func)
{
if (form == null)
{
throw new ArgumentNullException("form");
}
if (func == null)
{
throw new ArgumentNullException("func");
}
if (form.InvokeRequired)
{
return (T)form.Invoke(new Func<T>(func));
}
return func();
}
}
public static class UIInvokeHelper
{
/// <summary>
/// 适用于非耗时、无返回值的跨线程界面操作。
/// </summary>
/// <param name="form"></param>
/// <param name="action"></param>
public static void InvokeUI(this Form form, Action action)
{
if (form == null)
{
throw new ArgumentNullException("form");
}
if (action == null)
{
throw new ArgumentNullException("action");
}
if (form.InvokeRequired)
{
form.Invoke(new Action(action));
}
else
{
action();
}
}
/// <summary>
/// 适用于有返回值的跨线程界面操作。
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="form"></param>
/// <param name="func"></param>
/// <returns></returns>
public static T InvokeUI<T>(this Form form, Func<T> func)
{
if (form == null)
{
throw new ArgumentNullException("form");
}
if (func == null)
{
throw new ArgumentNullException("func");
}
if (form.InvokeRequired)
{
return (T)form.Invoke(new Func<T>(func));
}
return func();
}
/// <summary>
/// 适用于耗时、无返回值的跨线程界面操作。
/// </summary>
/// <param name="form"></param>
/// <param name="action"></param>
public static void BeginInvokeUI(this Form form, Action action)
{
if (form == null)
{
throw new ArgumentNullException("form");
}
if (action == null)
{
throw new ArgumentNullException("action");
}
if (form.InvokeRequired)
{
form.BeginInvoke(new Action(action));
}
else
{
Task.Factory.StartNew(action);
}
}
}