четверг, 27 мая 2010 г.

WPF - Проверка сети и "Update UI from different Thread"

Начал изучать WPF - проект в котором нестабильно работает inet
Надо проверять наличие его - отрисовываем текущий статус и подписываемся на смену статуса
В прямом вызове проблем нет, но вот из подписчика надо "Update UI from different Thread"
потому вот такой "хитрый" код в ShowInetStatus

public MainWindow()
{
InitializeComponent();

ShowInetStatus(ConnectionExists());
System.Net.NetworkInformation.NetworkChange.NetworkAvailabilityChanged +=new NetworkAvailabilityChangedEventHandler(NetworkChange_NetworkAvailabilityChanged);
}

bool ConnectionExists()
{
return System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable();
}
void ShowInetStatus(bool p)
{
Label theLabel = label1 as Label;
if (theLabel != null)
{
// Checking if this thread has access to the object.
if (theLabel.Dispatcher.CheckAccess())
{
// This thread has access so it can update the UI thread.
if (p)
theLabel.Content = "inet working";
else
theLabel.Content = "host not reachable.";
}
else
{
// This thread does not have access to the UI thread.
// Place the update method on the Dispatcher of the UI thread.
theLabel.Dispatcher.BeginInvoke(DispatcherPriority.Normal,
(Action)(() =>
{
if (p)
theLabel.Content = "inet working";
else
theLabel.Content = "host not reachable.";
}
));
}
}
}


Кроме того

Sacha Barber proposed a fantastic extension method that you might want to look into. It's called InvokeIfRequired, and looks a bit like this:
public static void InvokeIfRequired(this DispatcherControl control, Action operation)
{
if (control.Dispatcher.CheckAccess())
{
operation();
}
else
{
control.Dispatcher.BeginInvoke(DispatcherPriority.Normal, operation);
}
}
Then, it's simple to do:
Dispatcher.CurrentDispatcher.InvokeIfRequired(()=>{ theButton.Content="Hello"; });

Комментариев нет: