我需要在WPF向导控件上加载叠加层。我正在使用来自wpf extended tooklit的busyIndicator工具。
async await的代码有效但gui线程锁定。当await调用函数
时,我正在尝试添加请等待消息private async void Button1_Click(object sender, RoutedEventArgs e)
{
BusyIndicator.IsBusy = true;
BusyIndicator.IsEnabled = true;
BusyIndicator.BusyContent = "Please wait while Site is provisioned";
await Task.Run(() =>
{
LongRunningFunction();
});
BusyIndicator.IsBusy=false;
}
BusyIndicator的XAML如下所示。
<xctk:BusyIndicator x:Name="BusyIndicator" IsBusy="False" BusyContent="Please Wait">
</xctk:BusyIndicator>
LonRunningFunction是一个Webservice调用,它不更新UI只返回Bool值
public static bool LongRunningFunction(string URL)
{
bool IsPresent = CallWebservice()
return IsPresent;
}
问题
1)BusyIndicator似乎在异步调用之前没有触发,而是在LongRunning任务完成时似乎触发了
2)使用async和await时调用gui覆盖的正确过程是什么。
答案 0 :(得分:0)
这是我通过异步调用解决问题的方法
的上下文:强>
在这里,我使用MvvM
向您展示使用WPF
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Data;
using System.Windows.Input;
using System.Windows.Threading;
class VM
{
Dispatcher _dispatcher = Dispatcher.CurrentDispatcher;
//Time consuming operation
private void LongTask()
{
Thread.Sleep(5000);
//in here if you need to send something to the UI thread like an event use it like so:
_dispatcher.Invoke(new Action(() =>
{
//some code here to invoke an event
if (ComponentsLoaded != null)
ComponentsLoaded(this, new EventArgs { });
}));
}
private ICommand _command;
//This is the command to be used instead of click event handler
public ICommand Command
{
get { return _command; }
private set { _command = value; }
}
//method associated with ICommand
void commandMethod(object parameter)
{
Busy = true;
ThreadPool.QueueUserWorkItem(new WaitCallback(multiThreadTask));
Busy = false;
}
//the task to be started on another thread
void multiThreadTask(object parameter)
{
LongTask();
}
public event EventHandler ComponentsLoaded;
}
这是我在WPF中使用多个线程时使用的内容
你仍然可以在代码隐藏中使用它来实例化Dispatcher
并且你很高兴
如果您需要更多信息,请告诉我们。 HTH