Dispatcher.Invoke()
用于同步执行消息。它确保在调用该方法时,当前线程上的消息队列中的消息会被依次处理。使用Invoke方法时,当前线程会阻塞,直到指定的消息被处理完毕。
Dispatcher.BeginInvoke()
用于异步执行消息。它允许将消息委托给指定的线程池来处理,从而避免了阻塞当前线程。该方法接受一个代表操作的对象和一个可选的超时时间。使用BeginInvoke方法时,消息将立即传递给线程池处理,而不会等待操作完成。
private void Button_Click(object sender, RoutedEventArgs e)
{
Student student= Student();
student.Name='张三';
student.ClassName='1908C';
Thread thread = new Thread(new ParameterizedThreadStart(CheckStoreInfo));
thread.IsBackground = true;
thread.Start(student);
}
//在线程里是无法直接操作Ui控件和打开新窗口的。
public void CheckStoreInfo(object o)
{
Student model = (Student)o;
//方法一
Action action = () =>
{
txtStoreNo.Text = "1703A";
TipWindow tip = new TipWindow();
tip.Show();
};
//方法二
Dispatcher.BeginInvoke(new Action(() => {
txtStoreNo.Text = "1703B";
}));
//方法三
//App.Current.Dispatcher.BeginInvoke(new Action<string>(ShowTip_Dialog),"登录成功!");
//方法四 有参有返回值
int param1 = 1,param2 = 2;
object obj1 = Dispatcher.Invoke(new Func<int,int,int>(show),param1,param2)
}
public int show(int i, int k)
{
txtName.Text = "测试";
return i+k;
}
public void ShowTip_Dialog(string info)
{
TipWindow tip = new TipWindow();
tip.txtName.Text = tip.Name;
tip.txtClassName.Text = tip.ClassName;
tip.Show();
}
public class Student
{
public int ID { get; set; }
public string Name { get; set; }
public string ClassName { get; set; }
}