使用 Process 创建新的线程
private Process _ProcessSearch; private void InitializeProcess() { try { _ProcessSearch = new Process("Search"); _ProcessSearch.OnStart += _ProcessSearch_OnStart; _ProcessSearch.OnCompleted += _ProcessSearch_OnCompleted; } catch (PresentationException pex) { throw pex; } catch (Exception ex) { throw new PresentationException(ex); } }
启动线程
public void Search() { _ProcessSearch.Start(); }
在Start方法里通知UI线程
private void _ProcessSearch_OnStart(object sender, ProcessStartedEventArgs e) { try { Application.Current.Dispatcher.Invoke(() => YourMethod()); } catch (PresentationException pex) { pex.Report(); } catch (Exception ex) { new PresentationException(ex).Report(); } }
不会阻塞UI线程
Application.Current.Dispatcher.Invoke(() => YourMethod());
使用MVVM的话可以直接用
View.Dispatcher.Invoke(() => YourMethod());