简体   繁体   English

在同步操作上使用async / await(主要停留在UI线程上)

[英]Use async/await on synchronous operations (mainly to stay on UI thread)

I'm trying to run some stuff asynchronous. 我正在尝试异步运行一些东西。 Here's my code: 这是我的代码:

    private async void SearchButton_Click(object sender, EventArgs e)
    {
         await Search();
    }

    // Inside search there is no async operation
    public Task Search()
    {
        // search for data in DB
        // update DataGridView and other elements on UI

        // How to return null/void/nothing?
        return ???;
    }

Is it illegal/bad practice to await on synchronous methods like Search() ? 等待Search()类的同步方法是否非法/不好? I know I can use Task.Run(Search) instead but then Search() will be executed on another thread (not on UI thread) and I have to use Invoke() inside Search() very often. 我知道我可以改用Task.Run(Search)但是Search()将在另一个线程(而不是UI线程)上执行,并且我必须经常在Search()内使用Invoke()

I changed the return value of Search() method from 'void' to 'Task' so its awaitable but what do I have to return? 我将Search()方法的返回值从“无效”更改为“任务”,因此可以等待,但是我必须返回什么?

Is it illegal/bad practice to await on synchronous methods like Search()? 等待Search()之类的同步方法是否非法/不好?

Well it's a very bad idea, because your UI will hang, basically. 嗯,这是一个非常糟糕的主意,因为您的UI基本上会挂起。

You should change your Search method to SearchAsync (for the sake of convention) and use asynchronous database operations to make it properly asynchronous. 您应该将Search方法更改为SearchAsync (为了方便起见),并使用异步数据库操作使其正确异步。

Currently, you don't have any true asynchrony: everything will just happen on your UI thread. 当前,您没有任何真正的异步性:一切都将在您的UI线程上发生。

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

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