简体   繁体   English

使用分派器解除对Wpf Ui的阻止

[英]Using Dispatcher to unblock Wpf Ui

I am working on windows app which generates various results of testing. 我正在使用Windows应用程序,该应用程序会生成各种测试结果。 The UI provides a button Results which has various methods as event handlers. UI提供了一个按钮Results ,该按钮具有作为事件处理程序的各种方法。 These methods are provided by an API module. 这些方法由API模块提供。 The module fetches the data from warehouse and then displays it to the user. 该模块从仓库获取数据,然后将其显示给用户。 The API call is asynchronous. API调用是异步的。

But UI gets blocked once the button is clicked. 但是,一旦单击按钮,UI就会被阻止。 After quite some readings , I came to know that Dispatcher helps in running a process in background . 经过大量阅读之后,我知道Dispatcher有助于在后台运行进程。 Dispatcher can be invoked/call only by the UI thread. 调度程序只能由UI线程调用/调用。 How can I implement dispatcher to keep the UI away from being blocked? 如何实现调度程序以使UI不受阻塞?

The function in c# looks something like this C#中的函数看起来像这样

private async void get_results(object sender, RoutedEventArgs e)
{
      List<resultsummary> data = new List<resultsummary>();
      if(id==plan_id)
        {
           data= await getdata.getsummary(id, name);
         }           
} 

Edit:- 编辑:-

This is my understanding of async and await in the above code. 这是我对以上代码中异步和等待的理解。 But it gives an error cannot await . 但是它给出了一个错误cannot await The getdata class is in differnet namespace and the method getsummary is defined in that space. getdata类位于differnet命名空间中,并且方法getsummary在该空间中定义。

The main objective is to unblock the UI and how to go about this using Dispatcher technique? 主要目标是解锁UI,以及如何使用Dispatcher技术进行操作?

You don't need to use a Dispatcher to do what you want. 您无需使用Dispatcher即可完成所需的工作。 In order to fetch data on a background thread and then pass that data from the background thread to the UI thread, you can use the Task class . 为了获取后台线程上的数据,然后将其从后台线程传递到UI线程,可以使用Task

Task.Factory.StartNew((Func<YourDataType>)delegate()
{
    // Fetch data on background thread here (return YourDataType, whatever that is)
    return DataAccessClass.GetData();
}).ContinueWith((Task<YourDataType> task) =>
{
    // Update controls with result on UI thread here
    YourUiProperty = task.Result;
}, TaskScheduler.FromCurrentSynchronizationContext());

Obviously, you'll need to replace the YourDataType type with whatever your data type is. 显然,您需要用任何数据类型替换YourDataType类型。

You can use Action ... 您可以使用Action ...

Put your code in an Action like this" 将您的代码放入这样的Action

Action action = () =>
{
    // your code...
};

assume that you have a label to show result 假设您有一个标签来显示结果

myLabel.Dispatcher.BeginInvoke(action);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM