等待主方法中的SQL客户端异步

时间:2016-10-23 06:39:11

标签: c# .net asynchronous .net-core

我有这段代码:

Program.cs

using System;
using System.Collections.Generic;

namespace sql
{
    public class Program
    {
        public static void Main(string[] args)
        {
            var result = new List<SampleItem>();
            result = Inventory.QueryStock();

            foreach (var item in result)
            {
                Console.WriteLine("{0}", item.ItemCode);
            }
        }
    }
}

sql.cs

using System;
using System.Data;
using System.Data.SqlClient;
using System.Threading.Tasks;
using System.Collections.Generic;

namespace sql
{
    public class Inventory
    {
        public static async Task<List<SampleItem>> QueryStock()
        {
            if (Environment.GetEnvironmentVariable("SQL_CONNECTION_STRING") == null)
               Environment.SetEnvironmentVariable("SQL_CONNECTION_STRING","Data Source=myServer;Initial Catalog=myDataBase;user id=sa;password=sql@123");

            else 
                Console.WriteLine("sql connection already registered: ");

            var connectionString = Environment.GetEnvironmentVariable("SQL_CONNECTION_STRING");
            var sql = @"
                        SELECT
                            T0.ItemCode, T0.WhsCode, T0.OnHand, 
                            T1.AvgPrice, T0.OnHand * T1.AvgPrice as [Value]
                        FROM 
                            OITW T0
                        INNER JOIN
                            OITM T1 on T0.ItemCode = T1.ItemCode
                        WHERE
                            T0.itemcode LIKE 'RM%' AND T0.WhsCode ='RM' AND T0.onHand > 0";
            var items = new List<SampleItem>();

            using (var cnx = new SqlConnection(connectionString))
            {
                using (var cmd = new SqlCommand(sql, cnx))
                {
                    await cnx.OpenAsync();

                    using (var reader = await cmd.ExecuteReaderAsync(CommandBehavior.CloseConnection))
                    {
                        while (await reader.ReadAsync())
                        {
                            var item = new SampleItem
                                 {
                                     ItemCode = reader.GetString(0)
                                 };
                            items.Add(item);
                        }
                    }
               }
            }

            return items;
        } 
    }

    public class SampleItem
    {
        public string ItemCode { get; set; }
    }
}

并将所需的依赖项System.Data.SqlClient添加到JSON文件中以获取:

project.json

{
  "version": "1.0.0-*",
  "buildOptions": {
    "debugType": "portable",
    "emitEntryPoint": true
  },
  "dependencies": {
        "System.Data.SqlClient": "4.1.0"
  },
  "frameworks": {
    "netcoreapp1.0": {
      "dependencies": {
        "Microsoft.NETCore.App": {
          "type": "platform",
          "version": "1.0.1"
        }
      },
      "imports": "dnxcore50"
    }
  }
}

问题是我QueryStock()返回的异步结果未在Main函数中捕获,因为await未存在,如果我使用await然后它要求Mainasync,如果我做了async,它会告诉Entry point Main不能async

更新

考虑到问题已被阻止以获得答案,我只是重新撰写Rubbke评论,该问题通过问题解决,以便轻松捕捉:

result = Inventory.QueryStock().Result;

另一个我发现帮助的解决方案是:

result = Inventory.QueryStock().GetAwaiter().GetResult();

0 个答案:

没有答案