如何将方法转换为async / await C#

时间:2015-10-20 00:23:55

标签: c# async-await task-parallel-library

您好我的C#Web服务中有以下方法:

[WebMethod(EnableSession = true)]
        //[ScriptMethod(ResponseFormat = ResponseFormat.Json, UseHttpGet = true)]
        public object[] GetChartData()
        {

            System.Threading.Thread.Sleep(5000);

            string graphData = "";

            List<GoogleChartData> data = new List<GoogleChartData>();

            using (DBContext context = new DBContext ())
            {
                data = context.Campaings.AsNoTracking().Take(10).Select(c => new GoogleChartData
                {
                    Year = 2015,
                    USA = 1,
                    Mexico = 2,
                    Canada = 3
                }).ToList();
            }

            var chartData = new object[data.Count + 1];
            chartData[0] = new object[]{
                "Year",
                "USA",
                "Mexico",
                "Canada"
            };

            Random random = new Random();

            int j = 0;
            foreach (var i in data)
            {


                j++;
                chartData[j] = new object[] { i.Year.ToString(), random.Next(0, 1000), random.Next(0, 1000), random.Next(0, 1000) };
            }
            return  chartData;   

        }

我多次从同一个应用程序调用时遇到问题,所以我想让它异步。我是Async / Await的新手。

  

有任何线索吗?

2 个答案:

答案 0 :(得分:-1)

我不清楚你想要什么,但如果你想在你的功能中使用Await/Async,这是你的线索(假设你正在使用Entity Framework 6):

public async Task<object[]> GetChartData()
{
    List<GoogleChartData> data;
    using (DBContext context = new DBContext ())
    {
        data = await context.Campaings.AsNoTracking().Take(10).Select(c => new GoogleChartData
        {
            Year = 2015,
            USA = 1,
            Mexico = 2,
            Canada = 3
        }).ToListAsync(); // Use ToListAsync()
    }

    // The rest are the same
}

修改!!!

正如VAAA在评论中所说,ToListAsync()在他的情况下不可用,所以我尝试找到另一种解决方案。

感谢Scott Chamberlain在评论中的想法,解决方法是:使用来自来电者的Task.Run(() => GetChartData())

对于那些打算在Task.Run()内使用GetChartData()的人:我们应该 make asynchronous wrappers for synchronous code

答案 1 :(得分:-3)

看一看 Creating an async webservice method

[WemMethod]
public async Task<List<ErrorLog>> GetAllErrorLogs()
{
List<ErrorLog> errorLogs = new List<ErrorLog>();
await System.Threading.Tasks.Task.Run(() => {
    errorLogs = ErrorLogRepository.GetAllErrorLogs();
})
if (errorLogs == null)
    return new List<ErrorLog>();
return errorLogs;
}