C# 在后台操作的中间显示模式UI并继续
我有一个运行后台任务的WPF应用程序,它使用C# 在后台操作的中间显示模式UI并继续,c#,.net,wpf,asynchronous,async-await,C#,.net,Wpf,Asynchronous,Async Await,我有一个运行后台任务的WPF应用程序,它使用async/await。任务正在更新应用程序的状态UI。在此过程中,如果满足某个条件,我需要显示一个模式窗口,以使用户了解此类事件,然后继续处理,现在还需要更新该模式窗口的状态UI 这是我试图实现的一个草图版本: async Task AsyncWork(int n, CancellationToken token) { // prepare the modal UI window var modalUI = new Window();
async/await
。任务正在更新应用程序的状态UI。在此过程中,如果满足某个条件,我需要显示一个模式窗口,以使用户了解此类事件,然后继续处理,现在还需要更新该模式窗口的状态UI
这是我试图实现的一个草图版本:
async Task AsyncWork(int n, CancellationToken token)
{
// prepare the modal UI window
var modalUI = new Window();
modalUI.Width = 300; modalUI.Height = 200;
modalUI.Content = new TextBox();
using (var client = new HttpClient())
{
// main loop
for (var i = 0; i < n; i++)
{
token.ThrowIfCancellationRequested();
// do the next step of async process
var data = await client.GetStringAsync("http://www.bing.com/search?q=item" + i);
// update the main window status
var info = "#" + i + ", size: " + data.Length + Environment.NewLine;
((TextBox)this.Content).AppendText(info);
// show the modal UI if the data size is more than 42000 bytes (for example)
if (data.Length < 42000)
{
if (!modalUI.IsVisible)
{
// show the modal UI window
modalUI.ShowDialog();
// I want to continue while the modal UI is still visible
}
}
// update modal window status, if visible
if (modalUI.IsVisible)
((TextBox)modalUI.Content).AppendText(info);
}
}
}
异步任务异步工作(int n,CancellationToken)
{
//准备模式UI窗口
var modalUI=新窗口();
modalUI.宽度=300;modalUI.高度=200;
modalUI.Content=新文本框();
使用(var client=new HttpClient())
{
//主回路
对于(变量i=0;imodalUI.ShowDialog()
的问题在于它是一个阻塞调用,因此处理将停止,直到对话框关闭。如果窗口是非模态的,则不会有问题,但它必须是模态的,这取决于项目需求
有没有办法通过
async/await
解决这个问题?这可以通过异步执行modalUI.ShowDialog()。下面的ShowDialogAsync实现是通过使用TaskCompletionSource
()和SynchronizationContext.Post
实现的
这样的执行工作流可能有点难以理解,因为您的异步任务现在分布在两个独立的WPF消息循环中:主线程的循环和新的嵌套循环(由ShowDialog
启动)。在我看来,这很好,我们只是利用了C#编译器提供的async/await
状态机
尽管如此,当任务结束时模式窗口仍然打开,您可能需要等待用户关闭它。这就是CloseDialogAsync
在下面所做的。此外,您可能应该解释当用户关闭任务中间的对话框时(AFAIK,WPF窗口不能重复使用多个代码>显示对话框< /COD>调用)。
以下代码适用于我:
using System;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
namespace WpfAsyncApp
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
this.Content = new TextBox();
this.Loaded += MainWindow_Loaded;
}
// AsyncWork
async Task AsyncWork(int n, CancellationToken token)
{
// prepare the modal UI window
var modalUI = new Window();
modalUI.Width = 300; modalUI.Height = 200;
modalUI.Content = new TextBox();
try
{
using (var client = new HttpClient())
{
// main loop
for (var i = 0; i < n; i++)
{
token.ThrowIfCancellationRequested();
// do the next step of async process
var data = await client.GetStringAsync("http://www.bing.com/search?q=item" + i);
// update the main window status
var info = "#" + i + ", size: " + data.Length + Environment.NewLine;
((TextBox)this.Content).AppendText(info);
// show the modal UI if the data size is more than 42000 bytes (for example)
if (data.Length < 42000)
{
if (!modalUI.IsVisible)
{
// show the modal UI window asynchronously
await ShowDialogAsync(modalUI, token);
// continue while the modal UI is still visible
}
}
// update modal window status, if visible
if (modalUI.IsVisible)
((TextBox)modalUI.Content).AppendText(info);
}
}
// wait for the user to close the dialog (if open)
if (modalUI.IsVisible)
await CloseDialogAsync(modalUI, token);
}
finally
{
// always close the window
modalUI.Close();
}
}
// show a modal dialog asynchronously
static async Task ShowDialogAsync(Window window, CancellationToken token)
{
var tcs = new TaskCompletionSource<bool>();
using (token.Register(() => tcs.TrySetCanceled(), useSynchronizationContext: true))
{
RoutedEventHandler loadedHandler = (s, e) =>
tcs.TrySetResult(true);
window.Loaded += loadedHandler;
try
{
// show the dialog asynchronously
// (presumably on the next iteration of the message loop)
SynchronizationContext.Current.Post((_) =>
window.ShowDialog(), null);
await tcs.Task;
Debug.Print("after await tcs.Task");
}
finally
{
window.Loaded -= loadedHandler;
}
}
}
// async wait for a dialog to get closed
static async Task CloseDialogAsync(Window window, CancellationToken token)
{
var tcs = new TaskCompletionSource<bool>();
using (token.Register(() => tcs.TrySetCanceled(), useSynchronizationContext: true))
{
EventHandler closedHandler = (s, e) =>
tcs.TrySetResult(true);
window.Closed += closedHandler;
try
{
await tcs.Task;
}
finally
{
window.Closed -= closedHandler;
}
}
}
// main window load event handler
async void MainWindow_Loaded(object sender, RoutedEventArgs e)
{
var cts = new CancellationTokenSource(30000);
try
{
// test AsyncWork
await AsyncWork(10, cts.Token);
MessageBox.Show("Success!");
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
}
}
使用modalUI.Show()方法,尝试将主窗口的IshittesVisible设置为false(它可以防止在主窗口上触发事件),并更改opactiy(如果需要)…@Ravuthasamy,实际上我希望它的行为类似于(并且是!)普通模式窗口。我认为主要的问题是它在自己的消息循环上运行。这本质上是覆盖在屏幕的一部分,阻止用户与部分或全部UI交互吗?@JamieClayton,是的,本质上就是这样,而且我也希望用户能够与模式对话框UI交互,虽然主界面仍然被阻塞。谢谢,这似乎符合我的要求。我觉得我需要在调试器中逐步了解它,以便更好地理解它。@avo,顺便说一句,您可以使用Application.Current.Dispatcher.BeginInvoke
而不是SynchronizationContext.Post
。我想知道为什么.NET 4.5中没有添加ShowDialogAsync。真的应该这样。
async Task AsyncWork(int n, CancellationToken token)
{
// prepare the modal UI window
var modalUI = new Window();
modalUI.Width = 300; modalUI.Height = 200;
modalUI.Content = new TextBox();
Task modalUITask = null;
try
{
using (var client = new HttpClient())
{
// main loop
for (var i = 0; i < n; i++)
{
token.ThrowIfCancellationRequested();
// do the next step of async process
var data = await client.GetStringAsync("http://www.bing.com/search?q=item" + i);
// update the main window status
var info = "#" + i + ", size: " + data.Length + Environment.NewLine;
((TextBox)this.Content).AppendText(info);
// show the modal UI if the data size is more than 42000 bytes (for example)
if (data.Length < 42000)
{
if (modalUITask == null)
{
// invoke modalUI.ShowDialog() asynchronously
modalUITask = Task.Factory.StartNew(
() => modalUI.ShowDialog(),
token,
TaskCreationOptions.None,
TaskScheduler.FromCurrentSynchronizationContext());
// continue after modalUI.Loaded event
var modalUIReadyTcs = new TaskCompletionSource<bool>();
using (token.Register(() =>
modalUIReadyTcs.TrySetCanceled(), useSynchronizationContext: true))
{
modalUI.Loaded += (s, e) =>
modalUIReadyTcs.TrySetResult(true);
await modalUIReadyTcs.Task;
}
}
}
// update modal window status, if visible
if (modalUI.IsVisible)
((TextBox)modalUI.Content).AppendText(info);
}
}
// wait for the user to close the dialog (if open)
if (modalUITask != null)
await modalUITask;
}
finally
{
// always close the window
modalUI.Close();
}
}