如何安全执行线程并执行并行任务,并行化和线程安全

时间:2019-06-13 07:05:30

标签: c# multithreading async-await thread-safety

我想优化我的代码,并在C#中使用安全的异步线程。我目前拥有的代码足以重复使用两次Task.WhenAll,我打算只使用其中一个,并确保任务是线程安全的并且并行的。

这是我目前的实现方式,我认为目前对我来说是最好的方法,但是任何人都可以建议使用更优化的版本。

 var tasks = new List<Task>();
// check for null reference for the items
if (results != null && results.items != null)
{
    // multithreaded might not be supported by the post request
    // changed to single thread for loop
    for(var i = 0; i < results.items.Count; i++) {
        var request = new PostAutoActionExecRequestJson()
        {
            ActionID = model.A_ID,
            Changes = new List<object>(),
            History = new HistoryJson()
            {
                Comment = model.Comment,
                DatastoreID = results.items[i].d_id,
                ItemID = results.items[i].i_id
            },
            RevNo = results.items[i].rev_no,
        };

        tasks.Add(services.PostAutoActionExecAsync<ExpandoObject>(request, token));
    }

    tasks.Add(CalculateNextExecution(model));
    await Task.WhenAll(tasks);
}

粘贴的代码应异步运行并同时完成任务。

请让我知道。

0 个答案:

没有答案
相关问题