简体   繁体   English

什么是创建等效功能的正确方法

[英]What is a proper way to create awaitable function

I have dilemma on how to actually create proper awaitable function. 我对如何真正创造适当的等待功能感到困惑。 I don't get the entire concept fully, probably due the language barrier :) 我没有完全理解整个概念,可能是由于语言障碍:)

A 一种

public async Task<int> InsertASync(string tableName, Dictionary<string, string> data)
    {
        int r = 0;

        using (SQLiteConnection con = NewConnection())
        {
            await con.OpenAsync();
            using (SQLiteCommand com = new SQLiteCommand(Query_Insert(tableName, data), con))
            {
                r = await com.ExecuteNonQueryAsync();
            }
            con.Close();
        }

        return r;
    }

or 要么

B

public Task<int> InsertASync(string tableName, Dictionary<string, string> data)
    {
        return Task<int>.Run(async () =>
            {
                int r = 0;

                using (SQLiteConnection con = NewConnection())
                {
                    await con.OpenAsync();
                    using (SQLiteCommand com = new SQLiteCommand(Query_Insert(tableName, data), con))
                    {
                        r = await com.ExecuteNonQueryAsync();
                    }
                    con.Close();
                }

                return r;
            });
    }

Reason i'm wondering about it is because the way i create awaitable methods via cheap way. 我想知道它的原因是因为我通过便宜的方式创造了可靠的方法。

Example

public void DoHeavyWork() //this will block UI
{
    //Do work
}

public Task DoHeavyWorkASync() //this won't
{
    return Task.Run(() =>
    {
         DoHeavyWork();
    });
}

You want to go the A route. 你想要走A路线。 The compiler will take care of creating the returned task and returning the actual integer, when available. 编译器将负责创建返回的任务并返回实际的整数(如果可用)。

You can read Asynchronous Programming - Pause and Play with ... for some good in-depth information on what the compiler does internally (how your method is converted into a state machine) 您可以阅读异步编程 - 暂停和播放...以获得有关编译器内部操作的一些详细深入信息(如何将方法转换为状态机)

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

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