Running several EntityFramework database queries in parallel

后端 未结 2 873
栀梦
栀梦 2020-12-31 06:05

I am trying to run 3 database queries in parallel but I\'m not sure that I am doing it correctly.

I have made 3 functions which each make a query to the database.

2条回答
  •  被撕碎了的回忆
    2020-12-31 06:45

    You will have to change the last part of the code to make it run in parallel:

    var taskAccountCode = getAccountCodeAsync(deviceId);
    var taskDeviceType = getDeviceTypeAsync(deviceId);
    var taskUsername = getUserNameAsync(userId);
    await Task.WhenAll(taskAccountCode, taskDeviceType, taskUsername);
    var accountCode = taskAccountCode.Result;
    var deviceType = taskDeviceType.Result;
    var username  = taskUsername.Result;
    

    Notice that there is only one await. In your original code you await every task one after the other making them run in sequence instead of in parallel.

    Also, the methods getAccountCodeAsync etc. are not really async methods (you should get a compiler warning about this). However, Entity Framework 6 has support for async operations and to use that you should replace FirstOrDefault with FirstOrDefaultAsync. For each parallel operation you will have to use a separate context, and that is exactly what you are doing.

提交回复
热议问题