我正在使用ShowMessageAsync方法使用MahApps Metro对话框。在某些情况下,我会调用对话框然后取消它。我正在调用对话框
MetroDialogSettings Settings = new MetroDialogSettings();
Settings.CancellationToken = Token;
Token.ThrowIfCancellationRequested();
await this.ShowMessageAsync("Prompt", "Prompt", MessageDialogStyle.Affirmative, Settings);
并以此取消
private void CancelDialog(CancellationTokenSource cts)
{
this.Dispatcher.Invoke(new Action(() => cts.Cancel()));
}
当我使用以下示例测试它时,这似乎工作得很好
Task.Delay(1000).ContinueWith(_=>CancelDialog(cs));
我还使用了Token。ThrowIfCancellationRequested();
,因为show和cancel之间存在异常。我的问题是,如果我在Show之前取消它可以正常工作,如果我在Show之后取消它会工作正常,但如果我在演出后0~500ms之间取消它会抛出NullReference异常。似乎MahApps代码中的某些内容并不正确,除非在完全初始化之前取消它。我试图找出一个方法来锁定它所以我只能取消一次初始化但我无法找到一种方法来判断它是否准备就绪?
更新
这简化为失败的原因。以下代码抛出NullRefernce异常
CancellationTokenSource cs = new CancellationTokenSource();
MetroDialogSettings settings = new MetroDialogSettings();
settings.CancellationToken = cs.Token;
this.ShowMessageAsync("Prompt", "Prompt", MessageDialogStyle.Affirmative, settings);
this.Dispatcher.Invoke(new Action(() => cs.Cancel()));
更新2: 这会导致异常:
CancellationTokenSource cs = new CancellationTokenSource();
MetroDialogSettings settings = new MetroDialogSettings();
settings.CancellationToken = cs.Token;
var result = this.ShowMessageAsync("Prompt", "Prompt", MessageDialogStyle.Affirmative, settings);
Task.Delay(400).ContinueWith(_ => this.Dispatcher.Invoke(new Action(() => cs.Cancel())));
虽然这不是:
CancellationTokenSource cs = new CancellationTokenSource();
MetroDialogSettings settings = new MetroDialogSettings();
settings.CancellationToken = cs.Token;
var result = this.ShowMessageAsync("Prompt", "Prompt", MessageDialogStyle.Affirmative, settings);
Task.Delay(500).ContinueWith(_ => this.Dispatcher.Invoke(new Action(() => cs.Cancel())));