Thread thread = new Thread(new ThreadStart(() =>
{
VisualTarget visualTarget = new VisualTarget(hostVisual);
var control = new UserControl1();
control.Arrange(new Rect(new Point(), content.RenderSize));
visualTarget.RootVisual = control;
System.Windows.Threading.Dispatcher.Run();
}));
thread.SetApartmentState(ApartmentState.STA);
thread.IsBackground = true;
thread.Start();
//同步步执行
System.Windows.Application.Current.Dispatcher.Invoke(() =>
{
//操作界面控件
});
beginInvoke //异步执行
System.Windows.Application.Current.Dispatcher.BeginInvoke(new Action(() =>
{
}));
//启用一个线程
Task.Factory.StartNew(() =>
{
});
//Task 为一种线程 CancellationTokenSource 控制Task 执行
- Task t1 = Task.Factory.StartNew(delegate { MyMethodA(); });
- Task t2 = Task.Factory.StartNew(delegate { MyMethodB(); });
- t1.Wait();
- t2.Wait();
下面是3中方式(摘取实例)
Control.CheckForIllegalCrossThreadCalls=false;来解决。设置为false表示不对错误线程的调用进行捕获。
线程自动定时执行
Task.Factory.StartNew<Update.UpdateConfig>(() =>
{
Thread.Sleep(3000);
bool isnew = Update.UpdateService.CheckNewVersion();
if (isnew)
{
UpdateConfig config=Update.UpdateService.GetNewVersion();
HasChecked = true;
return config;
}
return null;
}, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default)
.ContinueWith((e) =>
{
if (e.Exception == null)
{
if (e.Result != null)
{
Application.Current.Dispatcher.BeginInvoke(new Action(() =>
{
}));
}
}
});
委托界面传值
delegate void SafeSetText(string strMsg); private void SetText(string strMsg) { if(textbox1.InvokeRequired) { SafeSetText objSet=new SafeSetText(SetText); textbox1.Invoke(objSet,new object[]{strMsg}); } else { textbox1.Text=strMsg; } }
在线程内需要设置textbox的值时调用SetText方法既可。我们还可以采用另一种委托的方式来实现,那就是匿名代理,例如:
delegate void SafeSetText(string strMsg); private void SetText2(string strMsg) { SafeSetText objSet = delegate(string str) { textBox1.Text = str; } textBox1.Invoke(objSet,new object[]{strMsg}); }