我编写了以下代码来在 WPF 窗口中显示客户端发送的图像:
namespace ScreenStream
{
public partial class MainWindow : Window
{
private TcpListener _listener;
public MainWindow()
{
InitializeComponent();
StartServer();
}
private async void StartServer()
{
_listener = new TcpListener(IPAddress.Any, 12345);
_listener.Start();
while (true)
{
var client = await _listener.AcceptTcpClientAsync();
_ = Task.Run(() => HandleClient(client));
}
}
private async Task HandleClient(TcpClient client)
{
using (var networkStream = client.GetStream())
using (var memoryStream = new MemoryStream())
{
await networkStream.CopyToAsync(memoryStream);
memoryStream.Position = 0;
var bitmapImage = new BitmapImage();
bitmapImage.BeginInit();
bitmapImage.StreamSource = memoryStream;
bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
bitmapImage.EndInit();
Dispatcher.Invoke(() =>
{
ScreenshotImage.Source = bitmapImage;
});
}
client.Close();
}
protected override void OnClosed(EventArgs e)
{
_listener?.Stop();
base.OnClosed(e);
}
}
}
问题是ScreenshotImage.Source = bitmapImage;它会抛出错误System.InvalidOperationException: 'The calling thread cannot access this object because a different thread owns it.'。
我尝试以不同的方式声明它纯粹是无意义的Dispatcher,例如:
this.Dispatcher.Invoke(() =>
{
ScreenshotImage.Source = bitmapImage;
});
或者
Application.Current.Dispatcher.Invoke(() =>
{
ScreenshotImage.Source = bitmapImage;
});
但结果总是相同的,原则上这并不奇怪,而且我对如何解决问题没有任何其他想法,我用谷歌搜索了它,他们写到的任何地方都可以通过简单地添加来修复错误Dispatcher.Invoke,但是对于出于某种原因它对我没有帮助
问题是由于
BitmapImage它必须在主线程上初始化才能在Dispatcher.Invoke.尝试像这样
BitmapImage在内部创建和初始化:Dispatcher.Invoke