我创建了一个最小的WPF示例,展示了我在更复杂的容量中发现的令人困惑的问题。实质上,从外部线程获取带有Application.Current.MainWindow
的应用程序主窗口的引用可靠地抛出InvalidOperationException以进行跨线程对象访问。 只需阅读参考资料。然而!如果给定的MainWindow具有对存储在字段中的自身的引用,则可以毫无问题地读取该引用。它甚至可以被解除引用,例如访问其中一个属性。其他窗口字段也可以从其他线程读取和操作。为什么获取相同的引用(通过引用等于确认)交叉线程攻击或者不是跨线程攻击,具体取决于它的读取方式? Application.Current
是线程安全的,所以不应该责怪。 MainWindow
属性没有文档说明对其getter的亲和性检查。为什么会这样?
XAML for EXPERIMENT:
<Window x:Class="WPF_TEST.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WPF_TEST"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525" Background="Linen">
<Grid>
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition/>
<RowDefinition/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<Button Grid.Row="1" Grid.Column="1" Content="Test Handlers" Click="IReliablyExcept">
</Button>
</Grid>
</Window>
CODE_BEHIND FOR EXPERIMENT
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace WPF_TEST
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
private readonly MainWindow mainWindowField;
private bool someFlag = true;
public MainWindow()
{
mainWindowField = this;
InitializeComponent();
}
private async void IReliablyExcept(object sender, RoutedEventArgs e)
{
await Task.Run(() =>
{
var winRef = Application.Current.MainWindow;
});
}
private async void ButIDont(object sender, RoutedEventArgs e)
{
await Task.Run(() =>
{
var winRef = mainWindowField;
});
}
private async void IDontEither(object sender, RoutedEventArgs e)
{
await Task.Run(() =>
{
if (someFlag)
{
mainWindowField.Dispatcher.Invoke(() => { someFlag = false; });
}
});
}
}
}
Click事件处理程序可以重新连接以尝试所有三种变体。感谢您的任何见解。
答案 0 :(得分:1)
就是这样,因为Application.Current.MainWindow
属性检查调用线程是否具有访问权限。
这是反编译器属性的代码,this.VerifyAccess();
将可靠地抛出异常。
public Window MainWindow
{
get
{
this.VerifyAccess();
return this._mainWindow;
}
set
{
this.VerifyAccess();
if (this._mainWindow is RootBrowserWindow || this.BrowserCallbackServices != null && this._mainWindow == null && !(value is RootBrowserWindow))
throw new InvalidOperationException(SR.Get("CannotChangeMainWindowInBrowser"));
if (value == this._mainWindow)
return;
this._mainWindow = value;
}
}