Пример #1
0
        private void ProcessWork(Work work)
        {
            WorkerSynchronizationContext syncCtx = null;

            if (work.Options.HasFlag(WorkOptions.Post) && _isInAtomic)
            {
                syncCtx = new WorkerSynchronizationContext(this, _atomicWork);
                SynchronizationContext.SetSynchronizationContext(syncCtx);
            }
            else if (work.Sync != null || work.Options.HasFlag(WorkOptions.Atomic))
            {
                syncCtx = new WorkerSynchronizationContext(this, work);
                SynchronizationContext.SetSynchronizationContext(syncCtx);
            }

            Task task = null;

            try
            {
                task = work.Invoke();
            }
            catch (Exception e)
            {
                if (UnhandledException != null)
                {
                    UnhandledException(this, e);
                }
                else
                {
                    throw;
                }
            }

            if (syncCtx != null)
            {
                SynchronizationContext.SetSynchronizationContext(_synchronizationContext);
                if (work.Sync != null)
                {
                    if (task == null || work.Options.HasFlag(WorkOptions.Atomic) == false)
                    {
                        work.Sync.NotifySyncEndToWaiters();
                    }
                }
            }

            if (task != null)
            {
                Interlocked.Increment(ref _runningTaskCount);
                task.ContinueWith(OnTaskComplete, work, TaskContinuationOptions.ExecuteSynchronously);
            }
            else
            {
                if (work.CompletionSource != null)
                {
                    throw new InvalidOperationException("Function for InvokeResult should return Task");
                }
            }
        }
Пример #2
0
 public Worker(string name = null)
 {
     _synchronizationContext = new WorkerSynchronizationContext(this);
     _name = name;
 }