wpf 如何实现异步任务以使用异步和等待从数据库中获取数据?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26715569/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 12:40:36  来源:igfitidea点击:

How to implement Async Task to fetch data from database using async and await?

c#wpfmultithreadingasynchronousasync-await

提问by Ujaval Patel

I am doing this. It's working but is this a recommended way to do this. Please comments

我正在这样做。它正在工作,但这是推荐的方法吗?请评论

public async void LoadData()
{
    DataTable  dtAdditionsDetails = await LoadReportData(importID,
                                             InkeyCommon.ToInt32(cmbSellers.SelectedValue),
                                             fromDate,
                                             toDate);
    if (dtAdditionsDetails != null)
      dtaGrdAdditions.ItemSource = dtAdditionsDetails.DefaultView;
} 

public async Task<DataTable> LoadReportData(int? importID,
                                        int sellerID,
                                        DateTime? fromDate,
                                        DateTime? toDate)
{
    DataTable dtAdditionsDetails = new DataTable();

    //Get Report Data                                             
    await Task.Delay(1);

    dtAdditionsDetails = ReportsData.GetRptAdditions(importID,
                                  sellerID,
                                  fromDate,
                                  toDate);

    return dtAdditionsDetails;
}

采纳答案by Sheridan

In order to use the awaitkeyword properly, the object being 'awaited' should really be an ...Asyncmethod, like the GetStringAsyncmethod. As @ken2k has correctly pointed out, you cannot just awaitany method. Therefore, to answer your question is this a recommended way to do this?, the answer is no.

为了await正确使用关键字,“等待”的对象实际上应该是一个...Async方法,就像GetStringAsync方法一样。正如@ken2k 正确指出的那样,您不能只是await任何方法。因此,要回答您的问题,这是推荐的方法吗?, 答案是不。

You can find out how to use the awaitand asynckeywords correctly in the Asynchronous Programming with Async and Await (C# and Visual Basic)page on MSDN, however, if you're just trying to run a synchronous method asynchronously, then you can do that like this:

您可以在 MSDN 上的异步编程与 Async 和 Await(C# 和 Visual Basic)页面中找到如何正确使用awaitasync关键字,但是,如果您只是尝试异步运行同步方法,那么您可以这样做这个:

public DataTable LoadData()
{
    DataTable dtAdditionsDetails = ...
    // Get your data here synchronously
    return dtAdditionsDetails;
} 

public async Task<DataTable> LoadDataAsync()
{
    DataTable dtAdditionsDetails = LoadData();
    return Task.Run(() => LoadData());
} 

...

...

public async void GetDataAsynchronously()
{
    DataTable dtAdditionsDetails = await LoadDataAsync();
} 

Note that ...Asyncmethods (usually) return Task<T>objects, rather than nothing and that their names end in the word Async. Also note that only the data is returned from ...Asyncmethods and notthe Task<T>and that we don'tawaitwhen there is nothing to await.

请注意,...Async方法(通常)返回Task<T>对象,而不是什么都不返回,并且它们的名称以单词结尾Async。还要注意,只有数据从...Async方法返回,而不是Task<T>,当没有任何东西时我们不会awaitawait

回答by Mike Gledhill

Here's a simple function, to load a list of all [User]records from a database, using asyncand await.

这是一个简单的函数[User],使用async和加载数据库中所有记录的列表await

[HttpGet]
public async Task<IActionResult> Get()
{
    try
    {
        //  Fetch a list of all the [User] records, just for the hell of it.
        var users = await Task.Run(() => dbContextWebMgt.Users.ToList());
        return new OkObjectResult(users);
    }
    catch (Exception ex)
    {
        return new BadRequestObjectResult(ex.Message);
    }
}

回答by Bharat Bhushan Sharma

You can try like this using NPoco ORM

您可以尝试使用 NPoco ORM

[HttpGet]
public async Task<IActionResult> GetAsync()

{
      IList myList = await FetchAsync();
}