简体   繁体   中英

adding items asynchronously to a list within an async method in C# .NET

I'm trying to better understand await and asynchronous operations in C# and .NET. I have an object objectA which among other things contains a list of errors. I also have a list of ids and I need to perform an async method on each id. If my async method catches an error, I want to add that to objectA field that contains the list of errors. My worry is that this might not be thread safe as multiple threads might be trying to modify the same object at the same time. I don't care about the order of the errors. Is some type of locking automatically handled? Should I just return the error from the method and then add that to the list at the end?

Task Main()
{
    var objectA = new ExampleObject();
    List<Task> getIdtasks = new List<Task>();
    foreach (var id in ids)
    {
        tasks.Add(GetByIdAsync(id, objectA));
    }
    await Tasks.Whenall(getIdtasks)
}

private Task GetByIdAsync(object id, ExampleObject objectA)
{
    try
    {
        var objectFromId = await DoSomethingAsync(id)
        return objectFromId;
    }
    catch (Exception e)
    {
        objectA.errors.Add(e);
    }
    return null;

}

    

List is not Thread Safe. So if you try to do List.Add from different threads at hte same time it will fail.

You can use a lock for List.Add will solve the issue. OR

Use any Thread safe collections.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM