这与我的其他问题
How to cancel background printing有关.
我试图更好地理解CancellationTokenSource模型以及如何跨线程边界使用它.
我有一个主窗口(在UI线程上)后面的代码:
public MainWindow() { InitializeComponent(); Loaded += (s,e) => { DataContext = new MainWindowviewmodel(); Closing += ((MainWindowviewmodel)DataContext).MainWindow_Closing; }; }
private void CloseWindow(IClosable window) { if (window != null) { windowClosingCTS.Cancel(); window.Close(); } }
// Print Preview public static void PrintPreview(FixedDocument fixeddocument,CancellationToken ct) { // Was cancellation already requested? if (ct.IsCancellationRequested) ct.ThrowIfCancellationRequested(); ............................... // Use my custom document viewer (the print button is removed). var previewWindow = new PrintPreview(fixedDocumentSequence); //Register the cancellation procedure with the cancellation token ct.Register(() => previewWindow.Close() ); previewWindow.ShowDialog(); } }
在MainWindowviewmodel(在UI线程上),我把:
public CancellationTokenSource windowClosingCTS { get; set; }
其构造函数为:
// Constructor public MainMenu() { readers = new List<Reader>(); CloseWindowCommand = new RelayCommand<IClosable>(this.CloseWindow); windowClosingCTS = new CancellationTokenSource(); }
现在我的问题.当关闭UI线程上的MainWindow时,windowClosingCTS.Cancel()会立即调用使用ct注册的委托,即调用previewWindow.Close().这现在立即返回到“If(Windows!= null):
“The calling thread cannot access this object because a different
@H_301_30@
thread owns it.”那么我做错了什么?