Warten bis Laufwerk bereit async responsive UI

von

in

Aus irgend einem Grund hatte ich schon relativ oft das Problem, dass ich in einer Anwendung auf ein Laufwerk (Netzlaufwerk/Festplatte/Usb Stick) warten musste.

So habe ich es früher gemacht (GUI wird unbedienbar und hängt)

//short form without async await (annoying!)
private void WaitForDrive(string path)
{
	try
	{
		while (!Directory.Exists(path))
		{
			Thread.Sleep(1500);
		}
	}
	catch (Exception)
	{
		WaitForDrive(path); //try again, sometimes (rarely if thread sleep is long enough) accesstime is time tried -> exception
	}
}

//use it like that
WaitForDrive(@"E:\\");

Auch mit allen Thread Tricks und Dispatcher habe ich es nicht geschafft, dass das UI responsive bleibt. Nachdem ich mich intensiver mit async await auseinander gesetzt habe ist das derzeit meine verlässlichere Lösung mit der die GUI weiterhin bedienbar bleibt und eine Art Toast Message aufscheint:

//the async method
public async Task WaitForDriveAsync(string path, string waitingToastText)
{
	int width = 300;
	int height = 125;
	TextBlock toastTextBlock = new TextBlock() { Text = waitingToastText, HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Center, FontSize = 23, Width = (width - 15), TextWrapping = TextWrapping.WrapWithOverflow };
	Grid notification = new Grid();
	notification.Width = width;
	notification.Height = height;
	notification.Background = Brushes.Red;
	notification.Margin = new System.Windows.Thickness(0, 27, 0.4, 0);
	notification.VerticalAlignment = VerticalAlignment.Top;
	notification.HorizontalAlignment = HorizontalAlignment.Right;
	notification.Children.Add(toastTextBlock);

	grdMain.Children.Add(notification); //grdMain is the Name I have chosen for the WPF main Grid

	while (!Directory.Exists(path))
	{
		await Task.Delay(1000);
	}

	grdMain.Children.Remove(notification);
}

//to call it on btn click
private async void btnBackupNow_Click(object sender, RoutedEventArgs e)
{
	await WaitForDriveAsync(@"E:\", "Stecken Sie jetzt bitte die externe Festplatte am PC an.");
}

Kommentare

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert