Task operations

Scenario:

Setup users async way.

Solution:

Create multiple tasks to setup users and based on response add the details to collection and return. Also handle exceptions.
     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    using System.Collections.Concurrent;
    using System.Collections.Generic;
    using System.Linq;
    using System.Threading.Tasks;
    
    namespace ConsoleApplication1
    {
        class ProgramTaskErrorHandling
        {
            static void Main(string[] args)
            {
                var users = new List<User>() { };
                var items = SetupUsers(users);
            }
    
            private static async Task<List<User>> SetupUsers(List<User> users)
            {
                var tasks = new List<Task<List<User>>>();
    
                foreach (var user in users)
                {
                    tasks.Add(Setup(user));
                }
    
                //ConcurrentBag allows generic data to be stored in unordered from and is a thread-safe allowing multiple threads to use it. 
                var result = new ConcurrentBag<User>();
    
                while (tasks.Count > 0)
                {
                    var task = await Task.WhenAny(tasks).ConfigureAwait(false);
    
                    if (task.IsFaulted)
                    {
                        throw task.Exception == null ? new System.Exception("Task without exception") : task.Exception.Flatten().InnerExceptions[0];
                    }
    
                    if (!task.IsFaulted)
                    {
                        foreach (var item in task.Result)
                        {
                            result.Add(item);
                        }
                    }
    
                    tasks.Remove(task);
                }
    
                return result.ToList();
            }
    
            private static Task<List<User>> Setup(User user)
            {
                throw new System.NotImplementedException();
            }
        }
    
        internal class User
        {
        }
    }

No comments:

Post a Comment

Move Github Sub Repository back to main repo

 -- delete .gitmodules git rm --cached MyProject/Core git commit -m 'Remove myproject_core submodule' rm -rf MyProject/Core git remo...