【问题标题】:..how to return a Task<List<Model>> via c# and .net 4.0?..如何通过 c# 和 .net 4.0 返回 Task<List<Model>>?
【发布时间】:2020-07-11 16:29:38
【问题描述】:

我想返回一个任务 。 通过 c# 和 .net 4.0 vs2019。 不要使用异步。

        CancellationTokenSource source = new CancellationTokenSource();
        Task  List<AccountList> task1 = new Task List<AccountList>(() => {
           using (var db1 = new SqlConnection(DbHelper.AccountConStr))        

            {
                string sql = "select * from  AccountList where UseFlag='1'";
                try
                {
                    IEnumerable<AccountList> lst = db1.Query<AccountList>(sql);
                    return lst.ToList();
                }
                catch
                {
                    return new List<AccountList>();
                }
            }
        });
        task1.Start();
        while (timeout > sw.ElapsedMilliseconds)
        source.Cancel();
       

如何返回一个任务

【问题讨论】:

标签: c# task


【解决方案1】:

你为什么不能返回一个

Task&lt;List&lt;AccountList&gt;&gt;

即只返回task1。

然后在调用方法中,由于您没有 async/await,您可以使用 Task.ContinueWith(...) 来实现相同的目的。当任务解决时你想要做的事情在 ContinueWith 中。 Async / Await 只是语法糖。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-20
    • 2011-09-07
    相关资源
    最近更新 更多