コード例 #1
0
        public void Sequential_PostSendInsert_Success()
        {
            var expectedSequence = new List <object>();
            var resultSequence   = new List <object>();

            using (var synchronizationContext = new ThreadSynchronizationContext(ApartmentState.MTA))
            {
                for (var i = 0; i < 5; i++)
                {
                    expectedSequence.Add(i);

                    void SendOrPostCallback(object state)
                    {
                        lock (resultSequence)
                        {
                            resultSequence.Add(state);
                        }

                        Thread.Sleep(100);
                    }

                    synchronizationContext.Post(SendOrPostCallback, i);
                }

                var finishEvent = new ManualResetEvent(false);
                synchronizationContext.Post(state => finishEvent.Set(), null);

                synchronizationContext.Send(state => CollectionAssert.AreNotEqual(expectedSequence, resultSequence), null);

                finishEvent.WaitOne();
            }

            CollectionAssert.AreEqual(expectedSequence, resultSequence);
        }
コード例 #2
0
        public Task Broadcast(Type eventType, object args)
        {
            var subscriptions = new List <Delegate>();

            lock (_subscriptions)
            {
                var type = eventType;
                if (_subscriptions.ContainsKey(type))
                {
                    subscriptions.AddRange(_subscriptions[type]);
                }
            }

            var resultTasks = new List <Task>();

            foreach (var subscription in subscriptions)
            {
                var task = new Task(() => CallDelegate(subscription, args));
                task.SuppressError();
                resultTasks.Add(task);
            }

            try
            {
                void SendOrPostCallback(object state)
                {
                    foreach (var resultTask in resultTasks)
                    {
                        resultTask.Start();
                    }

                    try
                    {
                        Task.WhenAll(resultTasks).Wait(TimeSpan.FromSeconds(5));
                    }
                    catch (Exception)
                    {
                        //Nothing
                    }
                }

                _enqueueSynchronizationContext.Post(SendOrPostCallback, null);
            }
            catch (Exception e)
            {
                return(TaskHelper.FromException(e));
            }

            return(Task.WhenAll(resultTasks));
        }