public void ConcurrentDictionary()
        {
            var map = new ConcurrentDictionary <int, int>(8, 10000);
            var bag = new ConcurrentBag <int>();
            var completitionSources = new TaskCompletionSource <bool> [8];
            int initialID           = new Random().Next(1000000);

            for (int i = 0; i < completitionSources.Length; i++)
            {
                int j = i;
                completitionSources[j] = new TaskCompletionSource <bool>();
                new Thread(() =>
                {
                    ComplexTest(map, MapCapacity, bag, j + initialID);
                    completitionSources[j].SetResult(true);
                }).Start();
            }
            Task[] tasks = completitionSources.Select(t => t.Task).ToArray();
            Task.WaitAll(tasks);
            var errors = tasks.Where(t => t.IsFaulted).Select(t => t.Exception).ToArray();

            if (errors.Length > 0)
            {
                throw new AggregateException(errors);
            }
        }
        public static IEnumerable <Task <T> > WhenAny <T>(
            IEnumerable <Task <T> > tasks)
        {
            int nextTaskToComplete = -1;

            Task <T>[] tasksArray            = tasks.ToArray();
            var        taskCompletionSources =
                new TaskCompletionSource <T> [tasksArray.Length];


            for (int nTask = 0; nTask < tasksArray.Length; nTask++)
            {
                taskCompletionSources[nTask] = new TaskCompletionSource <T>();
                tasksArray[nTask].ContinueWith(t =>
                {
                    int nTaskCompleted = Interlocked.Increment(ref nextTaskToComplete);

                    if (t.Exception != null)
                    {
                    }


                    taskCompletionSources[nextTaskToComplete]
                    .SetResult(t.Result);
                });
            }

            return(taskCompletionSources.Select(t => t.Task));
        }
Beispiel #3
0
        /// <summary>
        /// Returns a sequence of tasks which will be observed to complete with the same set
        /// of results as the given input tasks, but in the order in which the original tasks complete.
        /// </summary>
        /// <typeparam name="T">The task result type.</typeparam>
        /// <param name="inputTasks">The tasks.</param>
        /// <returns>An enumeration of the completed tasks, in order of completion.</returns>
        /// <remarks>See <seealso cref="https://blogs.msmvps.com/jonskeet/2012/01/16/eduasync-part-19-ordering-by-completion-ahead-of-time/"/>.</remarks>
        public static IEnumerable <Task <T> > OrderByCompletion <T>(this IEnumerable <Task <T> > inputTasks)
        {
            var inputTaskList = inputTasks.ToList();

            var completionSources = new TaskCompletionSource <T> [inputTaskList.Count];

            for (int i = 0; i < inputTaskList.Count; i++)
            {
                completionSources[i] = new TaskCompletionSource <T>();
            }

            int prevIndex = -1;
            Action <Task <T> > continuation = completedTask =>
            {
                int index  = Interlocked.Increment(ref prevIndex);
                var source = completionSources[index];
                PropagateResult(completedTask, source);
            };

            foreach (var inputTask in inputTaskList)
            {
                inputTask.ContinueWith(continuation, TaskContinuationOptions.ExecuteSynchronously);
            }

            return(completionSources.Select(source => source.Task));
        }
        public void Test_AvailableWorkers()
        {
            var queue    = new AsyncTaskQueue(3);
            var tcsArray = new TaskCompletionSource[]
            {
                new TaskCompletionSource(),
                new TaskCompletionSource(),
                new TaskCompletionSource(),
            };
            List <Func <Task> > taskFuncs = tcsArray
                                            .Select <TaskCompletionSource, Func <Task> >(x => async() => await x.Task)
                                            .ToList();

            var task1 = queue.EnqueueAsync(taskFuncs[0]);

            Assert.Equal(2, queue.AvailableWorkers);

            var task2 = queue.EnqueueAsync(taskFuncs[1]);

            Assert.Equal(1, queue.AvailableWorkers);

            var task3 = queue.EnqueueAsync(taskFuncs[2]);

            Assert.Equal(0, queue.AvailableWorkers);
        }
        public async Task Should_Wait_For_Lock_Release_TaskOfT()
        {
            // Arrange
            var queue    = new AsyncTaskQueue(2);
            var tcsArray = new TaskCompletionSource <FakeType>[]
            {
                new TaskCompletionSource <FakeType>(),
                new TaskCompletionSource <FakeType>(),
                new TaskCompletionSource <FakeType>(),
            };

            tcsArray[2].SetResult(new FakeType()
            {
                Data = 3
            });

            List <Func <Task> > taskFuncs = tcsArray
                                            .Select <TaskCompletionSource <FakeType>, Func <Task> >(x => () => x.Task)
                                            .ToList();

            // Act
            var task1 = queue.EnqueueAsync(taskFuncs[0]);
            var task2 = queue.EnqueueAsync(taskFuncs[1]);
            var delay = new CancellationTokenSource(1000);
            var task3 = queue.EnqueueAsync(taskFuncs[2], delay.Token);

            // Assert
            await Assert.ThrowsAsync <OperationCanceledException>(async() =>
            {
                await task3;
            });
        }
Beispiel #6
0
        /// <summary>
        /// OrderByCompletionNaive has significant drawback - O(N^2) complexity and O(N^2) number of continuations.
        /// Current implemnetation should solve this issue.
        /// </summary>
        public static IEnumerable <Task <T> > OrderByCompletion <T>(this IEnumerable <Task <T> > taskSequence)
        {
            // Need to return task immediately, but it should be in complete state when the first task would be completed!
            Contract.Requires(taskSequence != null);

            var tasks = taskSequence.ToList();

            var taskCompletions = new TaskCompletionSource <T> [tasks.Count];

            int completedTask = -1;

            Action <Task <T> > continuation = tsk =>
            {
                var finishedTask = Interlocked.Increment(ref completedTask);
                taskCompletions[finishedTask].FromTask(tsk);
            };

            for (int i = 0; i < tasks.Count; i++)
            {
                taskCompletions[i] = new TaskCompletionSource <T>();
                tasks[i].ContinueWith(continuation);
            }

            return(taskCompletions.Select(tcs => tcs.Task));
        }
        public static IEnumerable <Task <T> > OrderByCompletion <T>(this IEnumerable <Task <T> > initialTasks)
        {
            var inputTasks   = initialTasks.ToList();
            var completions  = new TaskCompletionSource <T> [inputTasks.Count];
            int currentIndex = -1;

            for (int i = 0; i < inputTasks.Count; i++)
            {
                completions[i] = new TaskCompletionSource <T>();
                inputTasks[i].ContinueWith(completed =>
                {
                    currentIndex = Interlocked.Increment(ref currentIndex);
                    switch (completed.Status)
                    {
                    case TaskStatus.RanToCompletion:
                        completions[currentIndex].SetResult(completed.Result);
                        break;

                    case TaskStatus.Faulted:
                        completions[currentIndex].SetException(completed.Exception);
                        break;

                    case TaskStatus.Canceled:
                        completions[currentIndex].SetCanceled();
                        break;
                    }
                }, TaskContinuationOptions.ExecuteSynchronously);
            }

            return(completions.Select(x => x.Task));
        }
        public async Task Should_Complete_Task_After_Pool_Availability()
        {
            // Arrange
            var queue    = new AsyncTaskQueue(2);
            var tcsArray = new TaskCompletionSource[]
            {
                new TaskCompletionSource(),
                new TaskCompletionSource(),
                new TaskCompletionSource(),
            };

            tcsArray[2].SetResult();

            List <Func <Task> > taskFuncs = tcsArray
                                            .Select <TaskCompletionSource, Func <Task> >(x => () => x.Task)
                                            .ToList();

            // Act
            var task1 = queue.EnqueueAsync(taskFuncs[0]);
            var task2 = queue.EnqueueAsync(taskFuncs[1]);
            var task3 = queue.EnqueueAsync(taskFuncs[2]);

            // Assert
            Assert.False(task3.IsCompleted);
            Assert.Equal(TaskStatus.WaitingForActivation, task3.Status);

            tcsArray[0].SetResult();
            await task1;
            await task3;

            Assert.True(task3.IsCompleted);
        }
Beispiel #9
0
    static void Main(string[] args)
    {
        var context = new RootContext();

        Console.WriteLine($"Is Server GC {GCSettings.IsServerGC}");
        const int messageCount = 1000000;
        const int batchSize    = 100;

        Console.WriteLine("Dispatcher\t\tElapsed\t\tMsg/sec");
        var tps = new[] { 300, 400, 500, 600, 700, 800, 900 };

        foreach (var t in tps)
        {
            var d = new ThreadPoolDispatcher {
                Throughput = t
            };

            var clientCount = Environment.ProcessorCount * 1;
            var clients     = new PID[clientCount];
            var echos       = new PID[clientCount];
            var completions = new TaskCompletionSource <bool> [clientCount];

            var echoProps = Props.FromProducer(() => new EchoActor())
                            .WithDispatcher(d)
                            .WithMailbox(() => BoundedMailbox.Create(2048));

            for (var i = 0; i < clientCount; i++)
            {
                var tsc = new TaskCompletionSource <bool>();
                completions[i] = tsc;
                var clientProps = Props.FromProducer(() => new PingActor(tsc, messageCount, batchSize))
                                  .WithDispatcher(d)
                                  .WithMailbox(() => BoundedMailbox.Create(2048));

                clients[i] = context.Spawn(clientProps);
                echos[i]   = context.Spawn(echoProps);
            }
            var tasks = completions.Select(tsc => tsc.Task).ToArray();
            var sw    = Stopwatch.StartNew();
            for (var i = 0; i < clientCount; i++)
            {
                var client = clients[i];
                var echo   = echos[i];

                context.Send(client, new Start(echo));
            }
            Task.WaitAll(tasks);

            sw.Stop();
            var totalMessages = messageCount * 2 * clientCount;

            var x = (int)(totalMessages / (double)sw.ElapsedMilliseconds * 1000.0d);
            Console.WriteLine($"{t}\t\t\t{sw.ElapsedMilliseconds}\t\t{x}");
            Thread.Sleep(2000);
        }

        Console.ReadLine();
    }
Beispiel #10
0
        private static async Task DoClientWork()
        {
            const int messageCount = 1000000;
            const int batchSize    = 100;

            int[] clientCounts = new int[] { 1, 2, 4, 8, 16 };

            InitSilo();

            var clientConfig = ClientConfiguration.LocalhostSilo(3000);

            GrainClient.Initialize(clientConfig);

            Console.WriteLine("Clients\t\tElapsed\t\tMsg/sec");

            foreach (var clientCount in clientCounts)
            {
                var clients     = new IPingGrain[clientCount];
                var echos       = new IPongGrain[clientCount];
                var completions = new TaskCompletionSource <bool> [clientCount];

                for (var i = 0; i < clientCount; i++)
                {
                    var tsc = new TaskCompletionSource <bool>();
                    completions[i] = tsc;

                    clients[i] = GrainClient.GrainFactory.GetGrain <IPingGrain>(Guid.NewGuid());
                    echos[i]   = GrainClient.GrainFactory.GetGrain <IPongGrain>(Guid.NewGuid());
                }

                var tasks = completions.Select(tsc => tsc.Task).ToArray();
                var sw    = Stopwatch.StartNew();
                for (var i = 0; i < clientCount; i++)
                {
                    var client = clients[i];
                    var echo   = echos[i];

                    await client.Initialize(echo, 1);
                }
                Task.WaitAll(tasks);

                sw.Stop();
                var totalMessages = messageCount * 2 * clientCount;
                var x             = (int)(totalMessages / (double)sw.ElapsedMilliseconds * 1000.0d);
                Console.WriteLine($"{clientCount}\t\t{sw.ElapsedMilliseconds}\t\t{x}");

                Thread.Sleep(2000);
            }

            Console.ReadLine();
        }
Beispiel #11
0
        public static IEnumerable <Task <TTask> > ForEachAsync <TItem, TTask>(
            this IEnumerable <TItem> source, Func <TItem, Task <TTask> > selector,
            int degreeOfParallelism)
        {
            Contract.Requires(source != null);
            Contract.Requires(selector != null);

            // We need to know all the items in the source before starting tasks
            var tasks = source.ToList();

            int completedTask = -1;

            // Creating an array of TaskCompletionSource that would holds
            // the results for each operations
            var taskCompletions = new TaskCompletionSource <TTask> [tasks.Count];

            for (int n = 0; n < taskCompletions.Length; n++)
            {
                taskCompletions[n] = new TaskCompletionSource <TTask>();
            }

            // Partitioner would do all grunt work for us and split
            // the source into appropriate number of chunks for parallel processing
            foreach (var partition in
                     Partitioner.Create(tasks).GetPartitions(degreeOfParallelism))
            {
                var p = partition;

                // Loosing sync context and starting asynchronous
                // computation for each partition
                Task.Run(async() =>
                {
                    while (p.MoveNext())
                    {
                        var task = selector(p.Current);

                        // Don't want to use empty catch .
                        // This trick just swallows an exception
                        await task.ContinueWith(_ => { });

                        int finishedTaskIndex = Interlocked.Increment(ref completedTask);
                        taskCompletions[finishedTaskIndex].FromTask(task);
                    }
                });
            }

            return(taskCompletions.Select(tcs => tcs.Task));
        }
        public async Task OrderByCompletion_PropagatesCancelOnFirstCompletion()
        {
            var tcs     = new TaskCompletionSource <int>[] { new TaskCompletionSource <int>(), new TaskCompletionSource <int>() };
            var results = tcs.Select(x => x.Task).OrderByCompletion();

            tcs[1].SetCanceled();
            try
            {
                await results[0];
            }
            catch (OperationCanceledException)
            {
                return;
            }

            Assert.True(false);
        }
Beispiel #13
0
        private static async Task <int> Run(IConsole console, CancellationToken ct, int eventSize, int eventRate, BurstPattern burstPattern, int threads, int duration, int eventCount)
        {
            TimeSpan durationTimeSpan = TimeSpan.FromSeconds(duration);

            MySource.s_Payload = new String('a', eventSize);

            threadProc = makeThreadProc(eventCount);

            Thread[] threadArray = new Thread[threads];
            TaskCompletionSource <bool>[] tcsArray = new TaskCompletionSource <bool> [threads];

            for (int i = 0; i < threads; i++)
            {
                var tcs = new TaskCompletionSource <bool>();
                threadArray[i] = new Thread(() => { threadProc(); tcs.TrySetResult(true); });
                tcsArray[i]    = tcs;
            }

            Console.WriteLine($"SUBPROCESSS :: Running - Threads: {threads}, EventSize: {eventSize * sizeof(char):N} bytes, EventCount: {(eventCount == -1 ? -1 : eventCount * threads)}, EventRate: {(eventRate == -1 ? -1 : eventRate * threads)} events/sec, duration: {durationTimeSpan.TotalSeconds}s");
            Console.ReadLine();

            for (int i = 0; i < threads; i++)
            {
                threadArray[i].Start();
            }

            if (eventCount != -1)
            {
                Console.WriteLine($"SUBPROCESSS :: Sleeping for {durationTimeSpan.TotalSeconds} seconds or until {eventCount} events have been sent on each thread, whichever happens first");
            }
            else
            {
                Console.WriteLine($"SUBPROCESSS :: Sleeping for {durationTimeSpan.TotalSeconds} seconds");
            }

            Task threadCompletionTask = Task.WhenAll(tcsArray.Select(tcs => tcs.Task));
            Task result = await Task.WhenAny(Task.Delay(durationTimeSpan), threadCompletionTask);

            finished = true;

            await threadCompletionTask;

            Console.WriteLine("SUBPROCESSS :: Done. Goodbye!");
            return(0);
        }
        public async Task OrderByCompletion_PropagatesFaultOnFirstCompletion()
        {
            var tcs     = new TaskCompletionSource <int>[] { new TaskCompletionSource <int>(), new TaskCompletionSource <int>() };
            var results = tcs.Select(x => x.Task).OrderByCompletion();

            tcs[1].SetException(new InvalidOperationException("test message"));
            try
            {
                await results[0];
            }
            catch (InvalidOperationException ex)
            {
                Assert.Equal("test message", ex.Message);
                return;
            }

            Assert.True(false);
        }
Beispiel #15
0
        public static IEnumerable <Task <T> > OrderByCompletion <T>(this IEnumerable <Task <T> > tasks)
        {
            if (tasks == null)
            {
                throw new ArgumentNullException("tasks");
            }

            List <Task <T> > allTasks = tasks.ToList();

            if (allTasks.Count == 0)
            {
                throw new ArgumentException("Must have at least one task");
            }

            var taskCompletionsSources = new TaskCompletionSource <T> [allTasks.Count];

            int nextCompletedTask = -1;

            for (int nTask = 0; nTask < allTasks.Count; nTask++)
            {
                taskCompletionsSources[nTask] = new TaskCompletionSource <T>();
                allTasks[nTask].ContinueWith(t =>
                {
                    int taskToComplete = Interlocked.Increment(ref nextCompletedTask);
                    switch (t.Status)
                    {
                    case TaskStatus.RanToCompletion:
                        taskCompletionsSources[taskToComplete].SetResult(t.Result);
                        break;

                    case TaskStatus.Faulted:
                        taskCompletionsSources[taskToComplete].SetException(t.Exception.InnerExceptions);
                        break;

                    case TaskStatus.Canceled:
                        taskCompletionsSources[taskToComplete].SetCanceled();
                        break;
                    }
                }, TaskContinuationOptions.ExecuteSynchronously);
            }

            return(taskCompletionsSources.Select(tcs => tcs.Task));
        }
        public static IEnumerable <Task <TResult> > ForEachAsync <TItem, TResult>(
            this IEnumerable <TItem> source,
            Func <TItem, TResult> body,
            int degreeOfParallelism)
        {
            if (source == null)
            {
                throw new ArgumentNullException(nameof(source));
            }
            if (body == null)
            {
                throw new ArgumentNullException(nameof(body));
            }

            var sourceArray   = source.ToArray();
            var completedTask = -1;

            var taskCompletions = new TaskCompletionSource <TResult> [sourceArray.Length];

            for (var i = 0; i < taskCompletions.Length; i++)
            {
                taskCompletions[i] = new TaskCompletionSource <TResult>();
            }

            foreach (var partition in Partitioner.Create(sourceArray).GetPartitions(degreeOfParallelism))
            {
                Task.Run(
                    () =>
                {
                    while (partition.MoveNext())
                    {
                        var result = body(partition.Current);

                        var finishedTaskIndex = Interlocked.Increment(ref completedTask);
                        taskCompletions[finishedTaskIndex].SetResult(result);
                    }
                }
                    );
            }

            return(taskCompletions.Select(tcs => tcs.Task));
        }
Beispiel #17
0
        public void OrderByCompletion_PropagatesCancelOnFirstCompletion()
        {
            AsyncContext.Run(async() =>
            {
                var tcs     = new TaskCompletionSource <int>[] { new TaskCompletionSource <int>(), new TaskCompletionSource <int>() };
                var results = tcs.Select(x => x.Task).OrderByCompletion();

                tcs[1].SetCanceled();
                try
                {
                    await results[0];
                }
                catch (OperationCanceledException)
                {
                    return;
                }

                Assert.Fail();
            });
        }
Beispiel #18
0
        public static IEnumerable <Task <T> > InOrder <T>(this IEnumerable <Task <T> > tasks)
        {
            Task <T>[] tasksToComplete           = tasks.ToArray();
            var        taskCompSourcesToComplete = new TaskCompletionSource <T> [tasksToComplete.Length];

            int nextTaskIndex = -1;

            for (int i = 0; i < tasksToComplete.Length; i++)
            {
                taskCompSourcesToComplete[i] = new TaskCompletionSource <T>();
                tasksToComplete[i].ContinueWith(t =>
                {
                    // nextTaskIndex++;
                    var index = Interlocked.Increment(ref nextTaskIndex);
                    taskCompSourcesToComplete[index].SetResult(t.Result);
                });
            }

            return(taskCompSourcesToComplete.Select(tcs => tcs.Task));
        }
        public async Task OrderByCompletion_OrdersByCompletion()
        {
            var tcs     = new TaskCompletionSource <int>[] { new TaskCompletionSource <int>(), new TaskCompletionSource <int>() };
            var results = tcs.Select(x => x.Task).OrderByCompletion();

            Assert.False(results[0].IsCompleted);
            Assert.False(results[1].IsCompleted);

            tcs[1].SetResult(13);
            var result0 = await results[0];

            Assert.False(results[1].IsCompleted);
            Assert.Equal(13, result0);

            tcs[0].SetResult(17);
            var result1 = await results[1];

            Assert.Equal(13, result0);
            Assert.Equal(17, result1);
        }
Beispiel #20
0
        /// <summary>
        /// Process tasks in completion order. Based on Sergey Teplyakov' post:
        /// http://sergeyteplyakov.blogspot.ru/2015/06/process-tasks-by-completion.html
        /// </summary>
        /// <param name="tasks">Tasks sequence</param>
        /// <returns></returns>
        public static IEnumerable <Task> InCompletionOrder(this IEnumerable <Task> tasks)
        {
            var taskList = tasks.ToList();

            var taskCompletions = new TaskCompletionSource <object> [taskList.Count];

            int completedTask = -1;

            for (int i = 0; i < taskList.Count; i++)
            {
                taskCompletions[i] = new TaskCompletionSource <object>();
                taskList[i].ContinueWith(t =>
                {
                    var nextIdx = Interlocked.Increment(ref completedTask);
                    taskCompletions[nextIdx].Propagate(t);
                });
            }

            return(taskCompletions.Select(tcs => tcs.Task));
        }
Beispiel #21
0
        public void OrderByCompletion_PropagatesFaultOnFirstCompletion()
        {
            AsyncContext.Run(async() =>
            {
                var tcs     = new TaskCompletionSource <int>[] { new TaskCompletionSource <int>(), new TaskCompletionSource <int>() };
                var results = tcs.Select(x => x.Task).OrderByCompletion();

                tcs[1].SetException(new InvalidOperationException("test message"));
                try
                {
                    await results[0];
                }
                catch (InvalidOperationException ex)
                {
                    Assert.AreEqual("test message", ex.Message);
                    return;
                }

                Assert.Fail();
            });
        }
        public void Test_IsFull()
        {
            var queue    = new AsyncTaskQueue(2);
            var tcsArray = new TaskCompletionSource[]
            {
                new TaskCompletionSource(),
                new TaskCompletionSource(),
                new TaskCompletionSource(),
            };
            List <Func <Task> > taskFuncs = tcsArray
                                            .Select <TaskCompletionSource, Func <Task> >(x => async() => await x.Task)
                                            .ToList();

            var task1 = queue.EnqueueAsync(taskFuncs[0]);

            Assert.False(queue.IsFull);

            var task2 = queue.EnqueueAsync(taskFuncs[1]);

            Assert.True(queue.IsFull);
        }
Beispiel #23
0
        public void OrderByCompletion_OrdersByCompletion()
        {
            AsyncContext.Run(async() =>
            {
                var tcs     = new TaskCompletionSource <int>[] { new TaskCompletionSource <int>(), new TaskCompletionSource <int>() };
                var results = tcs.Select(x => x.Task).OrderByCompletion();

                Assert.IsFalse(results[0].IsCompleted);
                Assert.IsFalse(results[1].IsCompleted);

                tcs[1].SetResult(13);
                var result0 = await results[0];
                Assert.IsFalse(results[1].IsCompleted);
                Assert.AreEqual(13, result0);

                tcs[0].SetResult(17);
                var result1 = await results[1];
                Assert.AreEqual(13, result0);
                Assert.AreEqual(17, result1);
            });
        }
Beispiel #24
0
        public Task InProcessPingPong()
        {
            var d = new ThreadPoolDispatcher {
                Throughput = Tps
            };

            var clientCount = Environment.ProcessorCount * 1;
            var clients     = new PID[clientCount];
            var echos       = new PID[clientCount];
            var completions = new TaskCompletionSource <bool> [clientCount];

            var echoProps = Props.FromProducer(() => new EchoActor())
                            .WithDispatcher(d)
                            .WithMailbox(() => BoundedMailbox.Create(2048));

            for (var i = 0; i < clientCount; i++)
            {
                var tsc = new TaskCompletionSource <bool>();
                completions[i] = tsc;

                var clientProps = Props.FromProducer(() => new PingActor(tsc, MessageCount, BatchSize))
                                  .WithDispatcher(d)
                                  .WithMailbox(() => BoundedMailbox.Create(2048));

                clients[i] = _context.Spawn(clientProps);
                echos[i]   = _context.Spawn(echoProps);
            }

            var tasks = completions.Select(tsc => tsc.Task).ToArray();

            for (var i = 0; i < clientCount; i++)
            {
                var client = clients[i];
                var echo   = echos[i];

                _context.Send(client, new Start(echo));
            }

            return(Task.WhenAll(tasks));
        }
Beispiel #25
0
 public void HopscotchMap()
 {
     var map = new HopscotchMap<int, int>(8, 10000);
     var bag = new ConcurrentBag<int>();
     var completitionSources = new TaskCompletionSource<bool>[8];
     int initialID = new Random().Next(1000000);
     for (int i = 0; i < completitionSources.Length; i++)
     {
         int j = i;
         completitionSources[j] = new TaskCompletionSource<bool>();
         new Thread(() =>
         {
             ComplexTest(map, MapCapacity, bag, j + initialID);
             completitionSources[j].SetResult(true);
         }).Start();
     }
     Task[] tasks = completitionSources.Select(t => t.Task).ToArray();
     Task.WaitAll(tasks);
     var errors = tasks.Where(t => t.IsFaulted).Select(t => t.Exception).ToArray();
     if (errors.Length > 0)
         throw new AggregateException(errors);
 }
        public static Task <Task <T> >[] WaitForAnyEx <T>(IEnumerable <Task <T> > tasks)
        {
            Task <T>[] toComplete = tasks.ToArray();

            var completionSources =
                new TaskCompletionSource <Task <T> > [toComplete.Length];

            int nextCompletedTask = -1;

            for (int i = 0; i < completionSources.Length; i++)
            {
                completionSources[i] = new TaskCompletionSource <Task <T> >();
                toComplete[i].ContinueWith(t =>
                {
                    completionSources[Interlocked.Increment(ref nextCompletedTask)]
                    .SetResult(t);
                });
            }


            return(completionSources.Select(tcs => tcs.Task).ToArray());
        }
Beispiel #27
0
        private static void Main(string[] args)
        {
            Console.WriteLine($"Is Server GC {GCSettings.IsServerGC}");
            var benchmarkSettings = Configuration.GetConfiguration <InprocBenchmarkSettings>("InprocBenchmarkSettings");

            var config     = ConfigurationFactory.ParseString(File.ReadAllText("akka-config.hocon"));
            var mainSystem = ActorSystem.Create("main", config);

            int messageCount   = benchmarkSettings.MessageCount;
            int batchSize      = benchmarkSettings.BatchSize;
            var dispatcherType = benchmarkSettings.DispatcherType;
            var mailboxType    = benchmarkSettings.MailboxType;

            Console.WriteLine("Dispatcher\t\tElapsed\t\tMsg/sec");
            var tps = benchmarkSettings.Throughputs;

            var msgSecs = new List <int>();

            foreach (var t in tps)
            {
                var clientCount = Environment.ProcessorCount * 1;
                var clients     = new IActorRef[clientCount];
                var echos       = new IActorRef[clientCount];
                var completions = new TaskCompletionSource <bool> [clientCount];

                var echoProps = Props.Create(typeof(EchoActor))
                                .WithDispatcher(dispatcherType)
                                .WithMailbox(mailboxType);

                for (var i = 0; i < clientCount; i++)
                {
                    var tsc = new TaskCompletionSource <bool>();
                    completions[i] = tsc;

                    var clientProps = Props.Create(() => new PingActor(tsc, messageCount, batchSize))
                                      .WithDispatcher(dispatcherType)
                                      .WithMailbox(mailboxType);

                    var clientLocalActorRef = (RepointableActorRef)mainSystem.ActorOf(clientProps);
                    SpinWait.SpinUntil(() => clientLocalActorRef.IsStarted);
                    clientLocalActorRef.Underlying.AsInstanceOf <ActorCell>().Dispatcher.Throughput = t;

                    var echoLocalActorRef = (RepointableActorRef)mainSystem.ActorOf(echoProps);
                    SpinWait.SpinUntil(() => echoLocalActorRef.IsStarted);
                    echoLocalActorRef.Underlying.AsInstanceOf <ActorCell>().Dispatcher.Throughput = t;

                    clients[i] = clientLocalActorRef;
                    echos[i]   = echoLocalActorRef;
                }

                var tasks = completions.Select(tsc => tsc.Task).ToArray();
                var sw    = Stopwatch.StartNew();
                for (var i = 0; i < clientCount; i++)
                {
                    var client = clients[i];
                    var echo   = echos[i];

                    client.Tell(new Start(echo));
                }

                Task.WaitAll(tasks);

                sw.Stop();
                var totalMessages = messageCount * 2 * clientCount;

                var x = (int)(totalMessages / (double)sw.ElapsedMilliseconds * 1000.0d);
                Console.WriteLine($"{t}\t\t\t{sw.ElapsedMilliseconds}\t\t{x}");
                msgSecs.Add(x);
                Thread.Sleep(2000);
            }

            Console.WriteLine($"Avg Msg/sec : {msgSecs.Average()}");
        }
    private static async Task Main()
    {
        var context = new RootContext(new ActorSystem());

        Console.WriteLine($"Is Server GC {GCSettings.IsServerGC}");
        const int messageCount = 1_000_000;
        const int batchSize    = 100;

        Console.WriteLine("ClientCount\t\tDispatcher\t\tElapsed\t\tMsg/sec");
        var tps = new[] { 50, 100, 200, 400, 800 };

        int[] clientCounts = { 4, 8, 16, 32 };

        foreach (var t in tps)
        {
            var d = new ThreadPoolDispatcher {
                Throughput = t
            };

            foreach (var clientCount in clientCounts)
            {
                var pingActor   = new PID[clientCount];
                var pongActor   = new PID[clientCount];
                var completions = new TaskCompletionSource <bool> [clientCount];

                var pongProps = Props.FromProducer(() => new PongActor())
                                .WithDispatcher(d);

                for (var i = 0; i < clientCount; i++)
                {
                    var tsc = new TaskCompletionSource <bool>();
                    completions[i] = tsc;
                    var pingProps = Props.FromProducer(() => new PingActor(tsc, messageCount, batchSize))
                                    .WithDispatcher(d);

                    pingActor[i] = context.Spawn(pingProps);
                    pongActor[i] = context.Spawn(pongProps);
                }

                var tasks = completions.Select(tsc => tsc.Task).ToArray();
                var sw    = Stopwatch.StartNew();

                for (var i = 0; i < clientCount; i++)
                {
                    var client = pingActor[i];
                    var echo   = pongActor[i];

                    context.Send(client, new Start(echo));
                }

                await Task.WhenAll(tasks);

                sw.Stop();
                var totalMessages = messageCount * 2 * clientCount;

                var x = ((int)(totalMessages / (double)sw.ElapsedMilliseconds * 1000.0d)).ToString("#,##0,,M",
                                                                                                   CultureInfo.InvariantCulture
                                                                                                   );
                Console.WriteLine($"{clientCount}\t\t\t{t}\t\t\t{sw.ElapsedMilliseconds} ms\t\t{x}");
                await Task.Delay(2000);
            }
        }
    }
Beispiel #29
0
        private static void Main(string[] args)
        {
            var benchmarkSettings = Configuration.GetConfiguration <InprocBenchmarkSettings>("InprocBenchmarkSettings");

            Console.WriteLine($"Is Server GC {GCSettings.IsServerGC}");
            int messageCount = benchmarkSettings.MessageCount;
            int batchSize    = benchmarkSettings.BatchSize;

            Console.WriteLine("Dispatcher\t\tElapsed\t\tMsg/sec");
            var tps = benchmarkSettings.Throughputs;

            var msgSecs = new List <int>();

            foreach (var t in tps)
            {
                var d = new ThreadPoolDispatcher {
                    Throughput = t
                };

                var clientCount = Environment.ProcessorCount * 1;
                var clients     = new PID[clientCount];
                var echos       = new PID[clientCount];
                var completions = new TaskCompletionSource <bool> [clientCount];

                var echoProps = Actor.FromProducer(() => new EchoActor())
                                .WithDispatcher(d)
                                .WithMailbox(() => benchmarkSettings.MailboxType == "bounded-mailbox" ? BoundedMailbox.Create(2048) : UnboundedMailbox.Create());

                for (var i = 0; i < clientCount; i++)
                {
                    var tsc = new TaskCompletionSource <bool>();
                    completions[i] = tsc;
                    var clientProps = Actor.FromProducer(() => new PingActor(tsc, messageCount, batchSize))
                                      .WithDispatcher(d)
                                      .WithMailbox(() => benchmarkSettings.MailboxType == "bounded-mailbox" ? BoundedMailbox.Create(2048) : UnboundedMailbox.Create());

                    clients[i] = Actor.Spawn(clientProps);
                    echos[i]   = Actor.Spawn(echoProps);
                }
                var tasks = completions.Select(tsc => tsc.Task).ToArray();
                var sw    = Stopwatch.StartNew();
                for (var i = 0; i < clientCount; i++)
                {
                    var client = clients[i];
                    var echo   = echos[i];

                    client.Tell(new Start(echo));
                }
                Task.WaitAll(tasks);

                sw.Stop();
                var totalMessages = messageCount * 2 * clientCount;

                var x = (int)(totalMessages / (double)sw.ElapsedMilliseconds * 1000.0d);
                Console.WriteLine($"{t}\t\t\t{sw.ElapsedMilliseconds}\t\t{x}");
                msgSecs.Add(x);
                Thread.Sleep(2000);
            }

            Console.WriteLine($"Avg Msg/sec : {msgSecs.Average()}");

            Console.ReadLine();
        }