Beispiel #1
0
        public BackgroundDispatcherAsync(
            [NotNull] IBackgroundExecution execution,
            [NotNull] Func <Guid, object, Task> action,
            [CanBeNull] object state,
            [NotNull] TaskScheduler taskScheduler,
            int maxConcurrency,
            bool ownsScheduler)
        {
            if (maxConcurrency <= 0)
            {
                throw new ArgumentOutOfRangeException(nameof(maxConcurrency));
            }

            _execution     = execution ?? throw new ArgumentNullException(nameof(execution));
            _action        = action ?? throw new ArgumentNullException(nameof(action));
            _state         = state;
            _taskScheduler = taskScheduler ?? throw new ArgumentNullException(nameof(taskScheduler));
            _ownsScheduler = ownsScheduler;

#if !NETSTANDARD1_3
            AppDomainUnloadMonitor.EnsureInitialized();
#endif

            _stopped = new CountdownEvent(maxConcurrency);

            for (var i = 0; i < maxConcurrency; i++)
            {
                Task.Factory.StartNew(
                    DispatchLoop,
                    CancellationToken.None,
                    TaskCreationOptions.None,
                    _taskScheduler).Unwrap();
            }
        }
        public BackgroundDispatcher(
            [NotNull] IBackgroundExecution execution,
            [NotNull] Action <Guid, object> action,
            [CanBeNull] object state,
            [NotNull] Func <ThreadStart, IEnumerable <Thread> > threadFactory)
        {
            if (threadFactory == null)
            {
                throw new ArgumentNullException(nameof(threadFactory));
            }

            _execution = execution ?? throw new ArgumentNullException(nameof(execution));
            _action    = action ?? throw new ArgumentNullException(nameof(action));
            _state     = state;

#if !NETSTANDARD1_3
            AppDomainUnloadMonitor.EnsureInitialized();
#endif

            var threads = threadFactory(DispatchLoop)?.ToArray();

            if (threads == null || threads.Length == 0)
            {
                throw new ArgumentException("At least one unstarted thread should be created.", nameof(threadFactory));
            }

            if (threads.Any(thread => thread == null || (thread.ThreadState & ThreadState.Unstarted) == 0))
            {
                throw new ArgumentException("All the threads should be non-null and in the ThreadState.Unstarted state.", nameof(threadFactory));
            }

            _stopped = new CountdownEvent(threads.Length);

            foreach (var thread in threads)
            {
                thread.Start();
            }
        }