Ejemplo n.º 1
0
        public EvoThreads(int threads, ThreadPriority priority)
        {
            // If the thread count is less than one or greater than the number of processors, throw an argument out of range exception
            if (threads < 1 || threads > Environment.ProcessorCount)
                throw new ArgumentOutOfRangeException("threads");

            // Initialize the threads array
            this._threads = new Thread[threads];

            // Initialize the event arrays
            this._resume = new AutoResetEvent[threads];
            this._waiting = new ManualResetEvent[threads];

            for (int i = 0; i < threads; i++)
            {
                // Create each thread in the threads array
                this._threads[i] = new Thread(new ParameterizedThreadStart(this.ThreadStart));

                //Set Priority
                this._threads[i].Priority = priority;

                // Set the properties for each thread in the threads array
                this._threads[i].IsBackground = true;

                // Create each element in the event arrays
                this._resume[i]  = new AutoResetEvent(false);
                this._waiting[i] = new ManualResetEvent(true);

                // Start each thread in the threads array
                this._threads[i].Start(i);
            }
        }
        public BackgroundTaskQueueProvider(ThreadPriority priority)
        {
            // set up the task queue
            _queue = new List<string>();

            // spin up the threads - two per logical CPU
            _maximumThreads = Environment.ProcessorCount * 2;
            #if DEBUG
            // if we're debugging, multithreading is a pain in the ass
            _maximumThreads = 1;
            #endif

            for (int i = 0; i < _maximumThreads; i++)
            {
                _threadStates.Add(i.ToString(), false);
            }

            for (int i = 0; i < _maximumThreads; i++)
            {
                Thread thread = new Thread(Processor)
                                     {
                                         Priority = priority,
                                         IsBackground = false,
                                         Name = i.ToString(CultureInfo.InvariantCulture)
                                     };
                thread.Start();
                _threadPool.Add(i.ToString(), thread);
            }
        }
Ejemplo n.º 3
0
        public bool StartServer(string strEventName, string strPipeName, CMD_CALLBACK_PROC pfnCmdProc, object pParam, ThreadPriority iThreadPriority, int iCtrlCmdEventID)
        {
            if (pfnCmdProc == null || strEventName.Length == 0 || strPipeName.Length == 0)
            {
                return false;
            }
            if (m_ServerThread != null)
            {
                return false;
            }

            PipeServerThread RunThread = new PipeServerThread(m_hStopEvent);
            RunThread.m_pCmdProc = pfnCmdProc;
            RunThread.m_pParam = pParam;
            RunThread.m_strEventName = strEventName;
            RunThread.m_strPipeName = strPipeName;
            RunThread.m_iCtrlCmdEventID = iCtrlCmdEventID;

            CommonUtil._ResetEvent(m_hStopEvent);
            m_ServerThread = new Thread(new ThreadStart(RunThread.Run));
            m_ServerThread.Priority = iThreadPriority;
            m_ServerThread.Start();

            return true;
        }
		public TaskSchedulerWithCustomPriority(int maxThreads, ThreadPriority threadPriority)
		{
			if (maxThreads < 1) throw new ArgumentOutOfRangeException("maxThreads");

			this.maxThreads = maxThreads;
			_threadPriority = threadPriority;
		}
Ejemplo n.º 5
0
 private ThumbnailSettings(Size size, InterpolationMode interpolationMode, Color backColor, ThreadPriority threadPriority)
 {
     this.size = size;
       this.interpolationMode = interpolationMode;
       this.backColor = backColor;
       this.threadPriority = threadPriority;
 }
Ejemplo n.º 6
0
 public Work()
 {
   _state = WorkState.INIT;
   _description = string.Empty;
   _priority = ThreadPriority.Normal;
   _eventArgs = new WorkEventArgs(this);
 }
Ejemplo n.º 7
0
		public ThreadWorker (IScheduler sched, ThreadWorker[] others, IProducerConsumerCollection<Task> sharedWorkQueue,
		                     bool createThread, int maxStackSize, ThreadPriority priority, EventWaitHandle handle)
		{
			this.others          = others;

			this.dDeque = new CyclicDeque<Task> ();
			
			this.sharedWorkQueue = sharedWorkQueue;
			this.workerLength    = others.Length;
			this.isLocal         = !createThread;
			this.waitHandle      = handle;
			
			this.childWorkAdder = delegate (Task t) { 
				dDeque.PushBottom (t);
				sched.PulseAll ();
			};
			
			// Find the stealing start index randomly (then the traversal
			// will be done in Round-Robin fashion)
			do {
				this.stealingStart = r.Next(0, workerLength);
			} while (others[stealingStart] == this);
			
			InitializeUnderlyingThread (maxStackSize, priority);
		}
Ejemplo n.º 8
0
        /// <summary>
        /// Creates a new <c>SingleThreadExecutor</c> using a custom thread priority.
        /// </summary>
        /// <param name="priority">
        /// The priority to assign the thread.
        /// </param>
        public SingleThreadExecutor(ThreadPriority priority) {
            _actions = new BlockingQueue<Action>();
            _running = new AtomicBoolean(false);
            _shuttingDown = new AtomicBoolean(false);

            _priority = priority;
        }
Ejemplo n.º 9
0
		public ThreadWorker (IScheduler sched, ThreadWorker[] others, IProducerConsumerCollection<Task> sharedWorkQueue,
		                     bool createThread, int maxStackSize, ThreadPriority priority)
		{
			this.others          = others;

//			if (!string.IsNullOrEmpty (Environment.GetEnvironmentVariable ("USE_CYCLIC"))) {
//				Console.WriteLine ("Using cyclic deque");
//				this.dDeque = new CyclicDeque<Task> ();
//			} else {
//				this.dDeque = new DynamicDeque<Task> ();
//			}
			this.dDeque = new CyclicDeque<Task> ();
			
			this.sharedWorkQueue = sharedWorkQueue;
			this.workerLength    = others.Length;
			this.isLocal         = !createThread;
			
			this.childWorkAdder = delegate (Task t) { 
				dDeque.PushBottom (t);
				sched.PulseAll ();
			};
			
			// Find the stealing start index randomly (then the traversal
			// will be done in Round-Robin fashion)
			do {
				this.stealingStart = r.Next(0, workerLength);
			} while (others[stealingStart] == this);
			
			InitializeUnderlyingThread (maxStackSize, priority);
		}
Ejemplo n.º 10
0
		public SingleThreadTaskScheduler(string name = null, ThreadPriority priority = ThreadPriority.Normal, ApartmentState apartmentState = ApartmentState.STA)
		{
#if DEBUG
			_allocStackTrace = new StackTrace();
#endif

			_thread = new Thread(
				() =>
				{
					try
					{
						foreach (var task in _queue.GetConsumingEnumerable())
							TryExecuteTask(task);
					}
					finally
					{
						_queue.Dispose();
					}
				});

			_thread.IsBackground = true;
			_thread.Name = name;
			_thread.Priority = priority;
			_thread.SetApartmentState(apartmentState);

			_thread.Start();
		}
Ejemplo n.º 11
0
        /// <summary>
        /// Замеряет и выводит на экран время потраченное на решение уравнений с использованием потоков
        /// </summary>
        /// <param name="totalEquationCount">Общее количество уравнений которые необходимо решить. Делится между потоками</param>
        /// <param name="threadCount">Кол-во потоков которые следует использовать для параллельного решения уравнений</param>
        /// <param name="priority">Приоритет потока</param>
        private static void BenchmarkWithThreads(int totalEquationCount, int threadCount, ThreadPriority priority = ThreadPriority.Normal)
        {
            if (totalEquationCount % threadCount != 0) throw new Exception();

            Console.Write("Время на решение  с потоками: ");
            int itemsPerThread = totalEquationCount / threadCount; // Кол-во уравнений для каждого потока

            Stopwatch watch = Stopwatch.StartNew();
            Thread[] solveThreads = new Thread[threadCount];
            for (int i = 0, offset = 0; i < solveThreads.Length; i++, offset += itemsPerThread)
            {
                solveThreads[i] = new Thread(SolveThread)
                {
                    Name = String.Format("Решатель уравнений #{0}", i + 1),
                    Priority = priority
                };
                solveThreads[i].Start(itemsPerThread);
            }
            foreach (Thread solveThread in solveThreads)
            {
                solveThread.Join();
            }
            watch.Stop();
            Console.WriteLine("{0:F4} сек. Кол-во потоков: {1}. Приоритет: {2}", watch.Elapsed.TotalSeconds, threadCount, PriorityToString(priority));
        }
 public void ChangeThreadPriority(ThreadPriority priority)
 {
     if (_thread != null)
     {
         _thread.Priority = priority;
     }
 }
Ejemplo n.º 13
0
        /// <summary>
        /// Class constructor initializes fields from config file
        /// </summary>
        static NUnitConfiguration()
        {
            try
            {
                NameValueCollection settings = GetConfigSection("NUnit/TestCaseBuilder");
                if (settings != null)
                {
                    string oldStyle = settings["OldStyleTestCases"];
                    if (oldStyle != null)
                            allowOldStyleTests = Boolean.Parse(oldStyle);
                }

                settings = GetConfigSection("NUnit/TestRunner");
                if (settings != null)
                {
                    string apartment = settings["ApartmentState"];
                    if (apartment != null)
                        apartmentState = (ApartmentState)
                            System.Enum.Parse(typeof(ApartmentState), apartment, true);

                    string priority = settings["ThreadPriority"];
                    if (priority != null)
                        threadPriority = (ThreadPriority)
                            System.Enum.Parse(typeof(ThreadPriority), priority, true);
                }
            }
            catch (Exception ex)
            {
                string msg = string.Format("Invalid configuration setting in {0}",
                    AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
                throw new ApplicationException(msg, ex);
            }
        }
Ejemplo n.º 14
0
		internal PipeServiceClientChannel(PipeServiceClient client, ThreadPriority listenThreadPriority, int receiveTimeout, int sendTimeout)
		{
			this.client = client;

			this.receiveTimeout = receiveTimeout;
			this.sendTimeout = sendTimeout;
		}
Ejemplo n.º 15
0
 internal Thread(ThreadStart threadStart, ThreadPriority priority, SIP sip, TaskHandle task)
 {
     Task = task;
     _threadStart = threadStart;
     _priority = priority;
     _sip = sip;
 }
Ejemplo n.º 16
0
        public ThreadPool(int initialThreadCount, int maxThreadCount, string poolName,
                           int newThreadTrigger, int dynamicThreadDecayTime,
                           ThreadPriority threadPriority, int requestQueueLimit)
        {
            SafeWaitHandle = _stopCompleteEvent.SafeWaitHandle;

            if (maxThreadCount < initialThreadCount)
            {
                throw new ArgumentException("Maximum thread count must be >= initial thread count.", "maxThreadCount");
            }
            if (dynamicThreadDecayTime <= 0)
            {
                throw new ArgumentException("Dynamic thread decay time cannot be <= 0.", "dynamicThreadDecayTime");
            }
            if (newThreadTrigger <= 0)
            {
                throw new ArgumentException("New thread trigger time cannot be <= 0.", "newThreadTrigger");
            }
            ExceptionHelper.ThrowIfArgumentNullOrEmptyString(poolName, "poolName");

            _initialThreadCount = initialThreadCount;
            _maxThreadCount = maxThreadCount;
            _requestQueueLimit = (requestQueueLimit < 0 ? DEFAULT_REQUEST_QUEUE_LIMIT : requestQueueLimit);
            _decayTime = dynamicThreadDecayTime;
            _newThreadTrigger = new TimeSpan(TimeSpan.TicksPerMillisecond * newThreadTrigger);
            _threadPriority = threadPriority;
            _requestQueue = new Queue<WorkRequest>();

            _threadPoolName = poolName;
        }
Ejemplo n.º 17
0
 protected WorkerThread(string name, ThreadPriority priority, ApartmentState apartmentState)
 {
     _thread = new Thread(new ThreadStart(this.InternalRun));
     _thread.Name = name;
     _thread.Priority = priority;
     _thread.SetApartmentState(apartmentState);
 }
Ejemplo n.º 18
0
        public ThreadBackground(ThreadBackgroundFlags flags)
        {
            this.flags = flags;
            this.currentThread = Thread.CurrentThread;
            this.oldThreadPriority = this.currentThread.Priority;

            if ((flags & ThreadBackgroundFlags.Cpu) == ThreadBackgroundFlags.Cpu &&
                (activeFlags & ThreadBackgroundFlags.Cpu) != ThreadBackgroundFlags.Cpu)
            {
                this.currentThread.Priority = ThreadPriority.BelowNormal;
                activeFlags |= ThreadBackgroundFlags.Cpu;
            }

            if (Environment.OSVersion.Version >= OS.WindowsVista &&
                (flags & ThreadBackgroundFlags.IO) == ThreadBackgroundFlags.IO &&
                (activeFlags & ThreadBackgroundFlags.IO) != ThreadBackgroundFlags.IO)
            {
                IntPtr hThread = SafeNativeMethods.GetCurrentThread();
                bool bResult = SafeNativeMethods.SetThreadPriority(hThread, NativeConstants.THREAD_MODE_BACKGROUND_BEGIN);

                if (!bResult)
                {
                    NativeMethods.ThrowOnWin32Error("SetThreadPriority(THREAD_MODE_BACKGROUND_BEGIN) returned FALSE");
                }
            }

            activeFlags |= flags;

            ++count;
        }
        public void Repeat(string name, Action action, Action<Exception> onException, int interval = 100, ThreadPriority priority = ThreadPriority.Normal, CancellationToken? cancellationToken = null)
        {
            var thread = new Thread(
                () =>
                {
                    try
                    {
                        while (true)
                        {
                            if (cancellationToken.HasValue && cancellationToken.Value.IsCancellationRequested)
                                break;

                            Sleep(interval);
                            action();
                        }
                    }
                    catch (Exception e)
                    {
                        onException(e);
                    }
                }
            );
            thread.Run(priority);
            Register(thread, cancellationToken, name);
        }
Ejemplo n.º 20
0
 public static void SetThreadPriority(ThreadPriority priority)
 {
     if (Thread.CurrentThread.Priority != priority)
     {
         Thread.CurrentThread.Priority = priority;
     }
 }
Ejemplo n.º 21
0
 public static Thread InBackground(Action action, ThreadPriority priority)
 {
     Thread thread = new Thread(() => action());
     thread.Priority = priority;
     thread.IsBackground = true;
     thread.Start();
     return thread;
 }
Ejemplo n.º 22
0
 // Token: 0x06001841 RID: 6209
 // RVA: 0x00074ED0 File Offset: 0x000730D0
 public STPStartInfo()
 {
     this._performanceCounterInstanceName = SmartThreadPool.DefaultPerformanceCounterInstanceName;
     this._threadPriority = ThreadPriority.Normal;
     this._maxWorkerThreads = 25;
     this._idleTimeout = 60000;
     this._minWorkerThreads = 0;
 }
Ejemplo n.º 23
0
 /// <summary>
 /// Constructor with a custom thread priority
 /// </summary>
 /// <param name="priority">The underlying thread's priority</param>
 public Actor(ThreadPriority priority)
 {
     m_messageQueue = new Queue<Message>();
     m_waitHandle = new AutoResetEvent(false);
     m_thread = new Thread(MessagePump);
     m_thread.Priority = priority;
     m_thread.Start();
 }
Ejemplo n.º 24
0
 public STPStartInfo()
 {
     _performanceCounterInstanceName = SmartThreadPool.DefaultPerformanceCounterInstanceName;
     _threadPriority = SmartThreadPool.DefaultThreadPriority;
     _maxWorkerThreads = SmartThreadPool.DefaultMaxWorkerThreads;
     _idleTimeout = SmartThreadPool.DefaultIdleTimeout;
     _minWorkerThreads = SmartThreadPool.DefaultMinWorkerThreads;
 }
Ejemplo n.º 25
0
 public STPStartInfo(STPStartInfo stpStartInfo)
     : base(stpStartInfo)
 {
     _idleTimeout = stpStartInfo.IdleTimeout;
     _minWorkerThreads = stpStartInfo.MinWorkerThreads;
     _maxWorkerThreads = stpStartInfo.MaxWorkerThreads;
     _threadPriority = stpStartInfo.ThreadPriority;
     _performanceCounterInstanceName = stpStartInfo.PerformanceCounterInstanceName;
 }
Ejemplo n.º 26
0
 /// <summary>
 /// Creates a thread fiber.
 /// </summary>
 /// <param name="queue"></param>
 /// <param name="threadName"></param>
 /// <param name="isBackground"></param>
 /// <param name="priority"></param>
 public ThreadFiber(IQueue queue, string threadName, bool isBackground = true, ThreadPriority priority = ThreadPriority.Normal)
 {
     _queue = queue;
     _thread = new Thread(RunThread);
     _thread.Name = threadName;
     _thread.IsBackground = isBackground;
     _thread.Priority = priority;
     _scheduler = new Scheduler(this);
 }
Ejemplo n.º 27
0
        /// <summary>
        ///   Creates a new instance of the <see cref="WorkItem"/> class.
        /// </summary>
        protected WorkItem()
        {
            createdTime = DateTime.Now;
             priority = ThreadPriority.Normal;
             state = WorkItemState.Created;

             // Capture the invokers context.
             uiCulture = Thread.CurrentThread.CurrentUICulture;
        }
Ejemplo n.º 28
0
 public STPStartInfo(STPStartInfo stpStartInfo)
     : base(stpStartInfo)
 {
     _idleTimeout = stpStartInfo._idleTimeout;
     _minWorkerThreads = stpStartInfo._minWorkerThreads;
     _maxWorkerThreads = stpStartInfo._maxWorkerThreads;
     _threadPriority = stpStartInfo._threadPriority;
     _pcInstanceName = stpStartInfo._pcInstanceName;
 }
Ejemplo n.º 29
0
		public Scheduler (int maxWorker, int maxStackSize, ThreadPriority priority)
		{
			workQueue = new ConcurrentQueue<Task> ();
			workers = new ThreadWorker [maxWorker];
			
			for (int i = 0; i < maxWorker; i++) {
				workers [i] = new ThreadWorker (this, workers, workQueue, maxStackSize, priority);
			}
		}
Ejemplo n.º 30
0
 public AudioPipe(IAudioSource source, int size, bool own, ThreadPriority priority)
     : this(source.PCM, size)
 {
     this.own = own;
     this.priority = priority;
     _source = source;
     _sampleLen = _source.Length;
     _samplePos = _source.Position;
 }
Ejemplo n.º 31
0
 public static IDisposable SubscribeToLatestOnBGThread(this IObservable <Action> subject
                                                       , Action <Exception> onError, ThreadPriority priority = ThreadPriority.Normal)
 {
     return(subject.SubscribeToLatestOnBGThread(a => a(), onError, priority));
 }
Ejemplo n.º 32
0
 /// <summary>
 /// Set Priority of the thread
 /// </summary>
 /// <param name="priority">The priority of the thread</param>
 /// <returns>true if successfully set otherwise false</returns>
 public bool SetPriority(ThreadPriority priority)
 {
     m_threadPriority        = priority;
     m_threadHandle.Priority = priority;
     return(true);
 }
Ejemplo n.º 33
0
 internal void init(IceInternal.Instance instance, ThreadPriority priority, bool hasPriority)
Ejemplo n.º 34
0
 protected WorkerThreadBase(string name, ThreadPriority priority)
     : this(name, priority, false)
 {
 }
Ejemplo n.º 35
0
 /// <summary>
 /// Sets a value indicating the scheduling priority of a thread.
 /// </summary>
 /// <param name="newPriority">One of the <see cref="System.Threading.ThreadPriority"/> values.</param>
 public void SetPriority(ThreadPriority newPriority)
 {
     ProcessAPI.CeSetThreadPriority((uint)this.ThreadID, (int)newPriority);
 }
Ejemplo n.º 36
0
 /// <summary>
 /// Create a new <see cref="SimpleThreadPool" /> with the specified number
 /// of <see cref="Thread" /> s that have the given priority.
 /// </summary>
 /// <param name="threadCount">
 /// the number of worker <see cref="Thread" />s in the pool, must
 /// be > 0.
 /// </param>
 /// <param name="threadPriority">
 /// the thread priority for the worker threads.
 ///
 /// </param>
 public SimpleThreadPool(int threadCount, ThreadPriority threadPriority)
 {
     ThreadCount    = threadCount;
     ThreadPriority = threadPriority;
 }
Ejemplo n.º 37
0
 static extern bool SetThreadPriority(IntPtr hThread, ThreadPriority nPriority);
Ejemplo n.º 38
0
 public const int DefaultThreadPoolSize = -1; // Use the operating system default value
 public CustomThreadPool(string name, int threadPoolSize = DefaultThreadPoolSize, ThreadPriority priority = ThreadPriority.Normal)
 {
     if (threadPoolSize == DefaultThreadPoolSize)
     {
         int n;
         ThreadPool.GetMaxThreads(out _threadPoolSize, out n);
     }
     else
     {
         Debug.Assert(threadPoolSize > 0);
         _threadPoolSize = threadPoolSize;
     }
     _threads   = new List <CustomThreadPoolThread>();
     _semaphore = new Semaphore(_threadPoolSize, _threadPoolSize);
     Priority   = priority;
     Name       = name;
 }
 /// <summary>
 /// 更改指定线程的优先级。
 /// </summary>
 /// <param name="thread">指定的线程实例。</param>
 /// <param name="priority">需要设置的线程优先级。</param>
 public static void ChangeThreadPriority(Thread thread, ThreadPriority priority) => thread.Priority = priority;
Ejemplo n.º 40
0
 public PriorityScheduler(ThreadPriority priority)
 {
     _priority = priority;
 }
        public static DataLoader CreateDataLoader(string ConnectionStringName, DataFileInfo flFileInfo, int ThreadCount, ThreadPriority threadPriority, int CommitAfter)
        {
            ConnectionStringSettings settings = ConfigurationManager.ConnectionStrings[ConnectionStringName];

            switch (settings.ProviderName.ToUpper())
            {
            case "ORACLE":
                return(OracleDataLoader.CreateDataLoader(settings.ConnectionString, flFileInfo, ThreadCount, threadPriority, CommitAfter));

            case "SQLSERVER":
                return(SqlServerDataLoader.CreateDataLoader(settings.ConnectionString, flFileInfo, ThreadCount, threadPriority));
            }
            return(null);
        }
Ejemplo n.º 42
0
 private bool SetPriorityLive(ThreadPriority priority)
 {
     Debug.Assert(!_osHandle.IsInvalid);
     return(Interop.Kernel32.SetThreadPriority(_osHandle, (int)MapToOSPriority(priority)));
 }
Ejemplo n.º 43
0
 /// <summary>
 /// Start a new thread that is tracked by the watchdog timer.
 /// </summary>
 /// <param name="start">The method that will be executed in a new thread</param>
 /// <param name="name">A name to give to the new thread</param>
 /// <param name="priority">Priority to run the thread at</param>
 /// <param name="isBackground">True to run this thread as a background thread, otherwise false</param>
 /// <param name="alarmIfTimeout">Trigger an alarm function is we have timed out</param>
 /// <param name="log">If true then creation of thread is logged.</param>
 /// <returns>The newly created Thread object</returns>
 public static Thread StartThread(
     ThreadStart start, string name, ThreadPriority priority, bool isBackground, bool alarmIfTimeout, bool log = true)
 {
     return(StartThread(start, name, priority, isBackground, alarmIfTimeout, null, DEFAULT_WATCHDOG_TIMEOUT_MS, log));
 }
Ejemplo n.º 44
0
 private IEnumerator InternalDownloadAssets(AssetDownloader.DownloadState state, bool checkUpdates, bool isRetry, ThreadPriority threadPriority)
 {
     // ISSUE: object of a compiler-generated type is created
     return((IEnumerator) new AssetDownloader.\u003CInternalDownloadAssets\u003Ec__Iterator44()
     {
         checkUpdates = checkUpdates, isRetry = isRetry, threadPriority = threadPriority, state = state, \u003C\u0024\u003EcheckUpdates = checkUpdates, \u003C\u0024\u003EisRetry = isRetry, \u003C\u0024\u003EthreadPriority = threadPriority, \u003C\u0024\u003Estate = state, \u003C\u003Ef__this = this
     });
 }
Ejemplo n.º 45
0
 //Sets the priority of the threads
 public void SetPriority(ThreadPriority _priority)
 {
     this.backgroundWorker.Priority = _priority;
 }
Ejemplo n.º 46
0
 public static AssetDownloader.DownloadState StartTextDownload(bool checkUpdates, bool canRetry = true, ThreadPriority threadPriority = ThreadPriority.Normal)
 {
     if (AssetDownloader.mCoroutine != null || !checkUpdates && AssetDownloader.mRequestIDs.Count == 0 || AssetDownloader.mDownloadedText)
     {
         return((AssetDownloader.DownloadState)null);
     }
     if (AssetManager.Format != AssetManager.AssetFormats.Text)
     {
         AssetDownloader.mCachePath = AssetDownloader.mTextCachePath;
         AssetManager.Format        = AssetManager.AssetFormats.Text;
     }
     AssetDownloader.DownloadState state = new AssetDownloader.DownloadState();
     AssetDownloader.mRetryOnError = canRetry;
     AssetDownloader.mCoroutine    = AssetDownloader.Instance.StartCoroutine(AssetDownloader.Instance.InternalDownloadAssets(state, checkUpdates, false, threadPriority));
     return(state);
 }
Ejemplo n.º 47
0
 public WorkerQueue(ThreadPriority priority = ThreadPriority.Normal)
 {
     _priority = priority;
 }
Ejemplo n.º 48
0
 public FuncLooper(string id, ThreadPriority priority, int interval, Func <T> repeat)
     : base(id, priority, interval)
 {
     _repeat = repeat;
 }
Ejemplo n.º 49
0
        //
        // Only for use by Instance.
        //
#if !SILVERLIGHT
        internal Timer(IceInternal.Instance instance, ThreadPriority priority)
        {
            init(instance, priority, true);
        }
Ejemplo n.º 50
0
 public void WriteTo(FlushOutput flushOutputDelegate, CloseOutput closeOutputDelegate, ThreadPriority priority, object to)
 {
     if (flushOutputDelegate != null)
     {
         flushOutput += flushOutputDelegate;
     }
     if (closeOutputDelegate != null)
     {
         closeOutput += closeOutputDelegate;
     }
     _writeThread              = new Thread(FlushThread);
     _writeThread.Priority     = priority;
     _writeThread.IsBackground = true;
     _writeThread.Start(to);
 }
Ejemplo n.º 51
0
        /// <summary>
        /// 循环间隔运行
        /// </summary>
        /// <param name="doWork"></param>
        /// <param name="interval"></param>
        /// <param name="stopped"></param>
        /// <param name="isBackground"></param>
        /// <param name="priority"></param>
        /// <returns></returns>
        public static Thread PulseAction(Action doWork, TimeSpan interval, bool stopped = false, bool isBackground = true, ThreadPriority priority = ThreadPriority.Highest)
        {
            var td = Run(() =>
            {
                while (!stopped)
                {
                    doWork.Invoke();
                    Sleep((int)interval.TotalMilliseconds);
                }
            }, isBackground, priority);

            return(td);
        }
Ejemplo n.º 52
0
        public IWork Add(DoWorkHandler work, ThreadPriority threadPriority)
        {
            IWork w = new Work(work, threadPriority);

            return(Add(w) ? w : null);
        }
Ejemplo n.º 53
0
        public IWork Add(DoWorkHandler work, string description, QueuePriority queuePriority, ThreadPriority threadPriority, WorkEventHandler workCompletedHandler)
        {
            IWork w = new Work(work, description, threadPriority, workCompletedHandler);

            return(Add(w, queuePriority) ? w : null);
        }
Ejemplo n.º 54
0
 public static IDisposable SubscribeToLatestOnBGThread <TSource>(this IObservable <TSource> subject
                                                                 , Action <TSource> onNext, Action <Exception> onError, ThreadPriority priority = ThreadPriority.Normal)
 {
     return(subject.SubscribeToLatestOnBGThread(onNext, onError, () => { }, priority));
 }
        public static DataLoader CreateDataLoader(DbTypes DatabaseType, string ConnectionString, DataFileInfo flFileInfo, int ThreadCount, ThreadPriority threadPriority, int CommitAfter)
        {
            switch (DatabaseType)
            {
            case DbTypes.Oracle:
                return(OracleDataLoader.CreateDataLoader(ConnectionString, flFileInfo, ThreadCount, threadPriority, CommitAfter));

            case DbTypes.SqlServer:
                return(SqlServerDataLoader.CreateDataLoader(ConnectionString, flFileInfo, ThreadCount, threadPriority));
            }
            return(null);
        }
Ejemplo n.º 56
0
 public static IDisposable SubscribeToLatestOnBGThread <TSource>(this IObservable <TSource> subject
                                                                 , Action <TSource> onNext, Action <Exception> onError, Action onCompleted, ThreadPriority priority = ThreadPriority.Normal)
 {
     return(subject.Latest()
            .ToObservable(BGTreadSchedulerFactory(priority))
            .Subscribe(onNext, onError, onCompleted));
 }
Ejemplo n.º 57
0
        public IWorkItemResult QueueWorkItem <T>(Action <T> action, T item, bool background = true, ThreadPriority priority = ThreadPriority.Normal, WorkItemPriority itemPriority = WorkItemPriority.Normal)
        {
            var pool = getPool(background, priority, itemPriority);

            return(pool.QueueWorkItem(action, item, itemPriority));
        }
Ejemplo n.º 58
0
 private static bool SetPriority(ThreadPriority priority)
 {
     return(true);
 }
        public void RegisterHeldOffTask(DoMaintenanceDelegate do_maintenance_delegate, int delay_before_start_milliseconds, ThreadPriority thread_priority, int hold_off_level = 0, string extra_descr = "")
        {
            Utilities.LockPerfTimer l1_clk = Utilities.LockPerfChecker.Start();
            lock (do_maintenance_delegate_wrappers_lock)
            {
                l1_clk.LockPerfTimerStop();
                // Set up the wrapper
                DoMaintenanceDelegateWrapper do_maintenance_delegate_wrapper = new DoMaintenanceDelegateWrapper();
                do_maintenance_delegate_wrapper.maintainable_description = String.Format("{0}:{1}{2}", do_maintenance_delegate.Target, do_maintenance_delegate.Method.Name, extra_descr);
                do_maintenance_delegate_wrapper.target      = new WeakReference(do_maintenance_delegate.Target);
                do_maintenance_delegate_wrapper.method_info = do_maintenance_delegate.Method;
                do_maintenance_delegate_wrapper.delay_before_start_milliseconds = delay_before_start_milliseconds;
                do_maintenance_delegate_wrapper.hold_off_level = hold_off_level;
                do_maintenance_delegate_wrapper.daemon         = new Daemon("Maintainable:" + do_maintenance_delegate.Target.GetType().Name + "." + do_maintenance_delegate.Method.Name + extra_descr);

                // Add it to our list of trackers
                do_maintenance_delegate_wrappers.Add(do_maintenance_delegate_wrapper);

                // Start the thread
                do_maintenance_delegate_wrapper.daemon.Start(DaemonThreadEntryPoint, do_maintenance_delegate_wrapper);
                do_maintenance_delegate_wrapper.daemon.Priority = thread_priority;
            }
        }
    public void In(
        [FriendlyName("levelCount", "The total number of levels available.")]
        [SocketState(false, false)]
        out int levelCount,

        [FriendlyName("loadedLevel", "The level index that was last loaded.")]
        [SocketState(false, false)]
        out int[] loadedLevels,

        [FriendlyName("loadedLevelName", "The name of the level that was last loaded.")]
        [SocketState(false, false)]
        out string[] loadedLevelNames,

        [FriendlyName("isEditor", "Are we running inside the Unity editor?")]
        [SocketState(false, false)]
        out bool isEditor,

        [FriendlyName("isPlaying", "Returns true when in any kind of player.")]
        [SocketState(false, false)]
        out bool isPlaying,

#if !(UNITY_2017_2_OR_NEWER)
        [FriendlyName("isWebPlayer", "Are we running inside a web player?")]
        [SocketState(false, false)]
        out bool isWebPlayer,
#endif

        [FriendlyName("streamedBytes", "Returns the number of bytes that have been downloaded from the main unity web stream.")]
        [SocketState(false, false)]
        out int streamedBytes,

        [FriendlyName("platform", "Returns the platform the game is running (Read Only).")]
        [SocketState(false, false)]
        out RuntimePlatform platform,

        [FriendlyName("dataPath", "Contains the path to the game data folder (Read Only).")]
        [SocketState(false, false)]
        out string dataPath,

        [FriendlyName("persistentDataPath", "Contains the path to a persistent data directory (Read Only).")]
        [SocketState(false, false)]
        out string persistentDataPath,

        [FriendlyName("temporaryCachePath", "Contains the path to a temporary data / cache directory (Read Only).")]
        [SocketState(false, false)]
        out string temporaryCachePath,

#if !(UNITY_2017_2_OR_NEWER)
        [FriendlyName("srcValue", "The path to the web player data file relative to the html file (Read Only).")]
        [SocketState(false, false)]
        out string srcValue,
#endif

        [FriendlyName("absoluteURL", "The absolute path to the web player data file (Read Only).")]
        [SocketState(false, false)]
        out string absoluteURL,

        [FriendlyName("systemLanguage", "The language the user's operating system is running in.")]
        [SocketState(false, false)]
        out SystemLanguage systemLanguage,

        [FriendlyName("internetReachability", "Returns internet reachability status.")]
        [SocketState(false, false)]
        out NetworkReachability internetReachability,

        [FriendlyName("webSecurityEnabled", "Indicates whether Unity's webplayer security model is enabled.")]
        [SocketState(false, false)]
        out bool webSecurityEnabled,

        [FriendlyName("webSecurityHostUrl", "[This appears to be undocumented!]")]
        [SocketState(false, false)]
        out string webSecurityHostUrl,

        [FriendlyName("runInBackground", "Returns the application background play state.")]
        [SocketState(false, false)]
        out bool runInBackground,

        [FriendlyName("targetFrameRate", "Returns the frame rate the game is instructed to use. The value is the ideal frame rate and may not reflect the actual frame rate.")]
        [SocketState(false, false)]
        out int targetFrameRate,

        [FriendlyName("backgroundLoadingPriority", "Returns the priority of background loading thread.")]
        [SocketState(false, false)]
        out ThreadPriority backgroundLoadingPriority,

        [FriendlyName("unityVersion", "The version of the Unity runtime used to play the content.")]
        out string unityVersion
        )
    {
        levelCount = UnityEngine.SceneManagement.SceneManager.sceneCountInBuildSettings;

#if UNITY_5_3_0
        UnityEngine.SceneManagement.Scene[] scenes = UnityEngine.SceneManagement.SceneManager.GetAllScenes();
        loadedLevels     = new int[scenes.Length];
        loadedLevelNames = new string[scenes.Length];

        for (int i = 0; i < scenes.Length; i++)
        {
            loadedLevels[i]     = scenes[i].buildIndex;
            loadedLevelNames[i] = scenes[i].name;
        }
#else
        loadedLevels     = new int[UnityEngine.SceneManagement.SceneManager.sceneCount];
        loadedLevelNames = new string[UnityEngine.SceneManagement.SceneManager.sceneCount];

        for (int i = 0; i < UnityEngine.SceneManagement.SceneManager.sceneCount; i++)
        {
            UnityEngine.SceneManagement.Scene scene = UnityEngine.SceneManagement.SceneManager.GetSceneAt(i);
            loadedLevels[i]     = scene.buildIndex;
            loadedLevelNames[i] = scene.name;
        }
#endif

        isEditor = Application.isEditor;

        isPlaying = Application.isPlaying;
#if !(UNITY_2017_2_OR_NEWER)
        isWebPlayer = Application.isWebPlayer;
#endif
        streamedBytes = Application.streamedBytes;

        platform           = Application.platform;
        dataPath           = Application.dataPath;
        persistentDataPath = Application.persistentDataPath;
        temporaryCachePath = Application.temporaryCachePath;

#if !(UNITY_2017_2_OR_NEWER)
        srcValue = Application.srcValue;
#endif
        absoluteURL    = Application.absoluteURL;
        unityVersion   = Application.unityVersion;
        systemLanguage = Application.systemLanguage;

        internetReachability = Application.internetReachability;

#if !(UNITY_5_5_OR_NEWER || UNITY_2017 || UNITY_2018)
        webSecurityEnabled = Application.webSecurityEnabled;
        webSecurityHostUrl = Application.webSecurityHostUrl;
#else
        webSecurityEnabled = false;
        webSecurityHostUrl = "";
#endif

        backgroundLoadingPriority = Application.backgroundLoadingPriority;
        runInBackground           = Application.runInBackground;
        targetFrameRate           = Application.targetFrameRate;
    }