任务何时正确使用

时间:2015-11-05 19:37:29

标签: c# asp.net multithreading entity-framework asynchronous

我想使用EF async更新多个数据库实体。我有

[HttpPost]
    public ActionResult Update(StudentViewModel[] studentData)
    {
        try
        {
            IEnumerable<Task> tasksQuery = studentData.Select(async s => await UpdateStudentData(s));

            List<Task> tasks = tasksQuery.ToList();

            Task.WhenAll(tasks);

            return Json(new { success = true });
        }
        catch (EntityCommandExecutionException ex)
        {
            log.Warn(string.Format("{0}: {1}", "Operation Failed", ex.ToString()));
            return Json(new { success = false });
        }
    }

    private async Task UpdateStudentData(StudentViewModel sm)
    {
        var student= db.Students.FindAsync(sm.Id);
        if (student.Result != null)
        {
            student.Result.SectionId = sm.SectionId;
            student.Result.PreferenceOrder = sm.PreferenceOrder ;
            db.Entry(student.Result).State = EntityState.Modified;
            await db.SaveChangesAsync();
        }
    }

只需一次操作。我究竟做错了什么?我想更新所有实体而不是按顺序更新。

1 个答案:

答案 0 :(得分:1)

忽略此信息并查看更新

[HttpPost]
    public async Task<ActionResult> Update(StudentViewModel[] studentData) //notice async in this line
    {
        try
        {
            IEnumerable<Task> tasksQuery = studentData.Select(async s => await UpdateStudentData(s));

            List<Task> tasks = tasksQuery.ToList();

            await Task.WhenAll(tasks); //Notice await here

            return Json(new { success = true });
        }
        catch (EntityCommandExecutionException ex)
        {
            log.Warn(string.Format("{0}: {1}", "Operation Failed", ex.ToString()));
            return Json(new { success = false });
        }
    }

    private async Task UpdateStudentData(StudentViewModel sm)
    {
        var student= db.Students.FindAsync(sm.Id);
        if (student.Result != null)
        {
            student.Result.SectionId = sm.SectionId;
            student.Result.PreferenceOrder = sm.PreferenceOrder ;
            db.Entry(student.Result).State = EntityState.Modified;
            await db.SaveChangesAsync();
        }
    }

更新 - 我创建了以下示例代码并对其进行了测试

[HttpGet]
public async Task<JsonResult> Update() //notice async in this line and I have changed the return type
{
    try
    {
        var id = 0;
        //Create random data
        StudentViewModel[] studentData = new StudentViewModel[] {
        new StudentViewModel { ID = id++ }, new StudentViewModel { ID = id++ }, new StudentViewModel { ID = id++ }, new StudentViewModel { ID = id++ },
        new StudentViewModel { ID = id++ }, new StudentViewModel { ID = id++ }, new StudentViewModel { ID = id++ }, new StudentViewModel { ID = id++ },
        new StudentViewModel { ID = id++ }, new StudentViewModel { ID = id++ }, new StudentViewModel { ID = id++ }, new StudentViewModel { ID = id++ }
        };
        IEnumerable<Task> tasksQuery = studentData.Select(s => UpdateStudentData(s)); //Note there is no async and await in this line

        List<Task> tasks = tasksQuery.ToList();

        await Task.WhenAll(tasks); //Note await here

        return Json(new { success = true });
    }
    catch (Exception ex)
    {
        //log.Warn(string.Format("{0}: {1}", "Operation Failed", ex.ToString()));
        return Json(new { success = false });
    }
}

private async Task UpdateStudentData(StudentViewModel sm)
{
    await Task.Run(() =>
    {
        var sleepDelay = new Random().Next(500, 1000);
        Task.Delay(sleepDelay); //Add random sleep to prove that students are not processsesd in a sequence
        Debug.WriteLine($"ID: {sm.ID}, SleepDelay: {sleepDelay}");
    });         
}

public class StudentViewModel
{
    public int ID { get; internal set; }
}

以下是输出,请注意ID不是顺序的:)

ID: 0, SleepDelay: 868
ID: 1, SleepDelay: 868
ID: 3, SleepDelay: 787
ID: 4, SleepDelay: 966
ID: 2, SleepDelay: 868
ID: 6, SleepDelay: 743
ID: 7, SleepDelay: 661
ID: 8, SleepDelay: 520
ID: 9, SleepDelay: 520
ID: 10, SleepDelay: 520
ID: 11, SleepDelay: 520
ID: 5, SleepDelay: 564