public async Task Join_StopsTask()
        {
            AsyncContextThread context = new AsyncContextThread();
            Thread             thread  = await context.Factory.Run(() => Thread.CurrentThread).ConfigureAwait(false);

            await context.JoinAsync().ConfigureAwait(false);
        }
        /// <summary>
        /// Shuts the processing pipeline down (base class specific part).
        /// This method must not throw exceptions.
        /// </summary>
        internal override void OnShutdownBase()
        {
            // tell the processing thread to terminate
            // (it will try to process the last messages and exit)
            mTerminateProcessingTask = true;
            mAsyncProcessingCancellationTokenSource?.CancelAfter(mShutdownTimeout);
            mTriggerAsyncProcessingEvent?.Set();
            mAsyncProcessingTask?.Wait();

            // the processing task should have completed its work
            Debug.Assert(mAsyncProcessingTask == null || mAsyncProcessingTask.IsCompleted);

            // the stack should be empty now...
            Debug.Assert(mAsyncProcessingMessageStack == null || mAsyncProcessingMessageStack.UsedItemCount == 0);

            // clean up processing thread related stuff
            mAsyncContextThread?.Join();
            mAsyncProcessingCancellationTokenSource?.Dispose();
            mAsyncContextThread  = null;
            mAsyncProcessingTask = null;
            mAsyncProcessingCancellationTokenSource = null;
            mAsyncProcessingMessageStack            = null;

            // perform pipeline stage specific cleanup
            try
            {
                OnShutdown();
            }
            catch (Exception ex)
            {
                // swallow exception to avoid crashing the application, if the exception is not handled properly
                Debug.Fail("The pipeline stage failed shutting down.", ex.ToString());
            }
        }
Exemplo n.º 3
0
        public void ProgressReport_NotifiesChangeOnCapturedSynchronizationContext()
        {
            AsyncContext.Run(async() =>
            {
                SynchronizationContext updateContext = null;
                SynchronizationContext threadContext = null;

                var tcs = new TaskCompletionSource();
                using (var thread = new AsyncContextThread())
                {
                    threadContext = await thread.Factory.Run(() => SynchronizationContext.Current);
                    PropertyProgress <int> propertyProgress = await thread.Factory.Run(() => new PropertyProgress <int>());
                    propertyProgress.PropertyChanged       += (_, e) =>
                    {
                        updateContext = SynchronizationContext.Current;
                        tcs.SetResult();
                    };
                    IProgress <int> progress = propertyProgress;
                    progress.Report(13);
                    await tcs.Task;
                }

                Assert.IsNotNull(updateContext);
                Assert.AreEqual(threadContext, updateContext);
            });
        }
Exemplo n.º 4
0
        private async Task ExecuteWithChangedFsId(
            FtpExecutionContext context,
            ClaimsPrincipal unixUser,
            FtpCommandExecutionDelegate next)
        {
            var userId  = ConvertToLong(unixUser.FindFirst(FtpClaimTypes.UserId)?.Value) ?? uint.MaxValue;
            var groupId = ConvertToLong(unixUser.FindFirst(FtpClaimTypes.GroupId)?.Value) ?? uint.MaxValue;

            using (var contextThread = new AsyncContextThread())
            {
                await contextThread.Factory.Run(
                    async() =>
                {
                    using (new UnixFileSystemIdChanger(
                               _logger,
                               userId,
                               groupId,
                               _serverUser.UserId,
                               _serverUser.GroupId))
                    {
                        await next(context).ConfigureAwait(true);
                    }
                })
                .ConfigureAwait(true);

                await contextThread.JoinAsync().ConfigureAwait(false);
            }
        }
Exemplo n.º 5
0
        /// <summary>
        /// Execute a task asynchronously with Tweetinvi
        /// </summary>
        public static async Task <T> ExecuteTaskAsync <T>(Func <T> resultFunc)
        {
            // We store the credentials at the time of the call within the local memory
            var credentialsAtInvokeTime = CredentialsAccessor.CurrentThreadCredentials;

            // We are cloning to avoid changes to the settings before the async operation starts
            var sourceThreadSettingsClone = TweetinviConfig.CurrentThreadSettings.Clone();

            // The lambda expression will store 'credentialsAtInvokeTime' within a generated class
            // In order to keep the reference to the credentials at the time of invocation
            var operationRunWithSpecificCredentials = new Func <T>(() =>
            {
                TweetinviConfig.CurrentThreadSettings.InitialiseFrom(sourceThreadSettingsClone);

                // We get the newly created credentialsAccessor for the async thread (CredentialsAccessor are Thread specific)
                var credentialsAccessor = TweetinviContainer.Resolve <ICredentialsAccessor>();

                // We now use credentials of the lambda expression local variables to perform our operation
                //return AsyncContext.Run(() => credentialsAccessor.ExecuteOperationWithCredentials(credentialsAtInvokeTime, resultFunc));
                return(credentialsAccessor.ExecuteOperationWithCredentials(credentialsAtInvokeTime, resultFunc));
            });

            using (var thread = new AsyncContextThread())
            {
                var result = await thread.Factory.Run(() => { return(operationRunWithSpecificCredentials()); });

                return(result);
            }
        }
        public async Task Join_StopsTask()
        {
            var context = new AsyncContextThread();
            var thread  = await context.Factory.Run(() => Thread.CurrentThread);

            await context.JoinAsync();
        }
Exemplo n.º 7
0
 /// <summary>
 /// Cleans up.
 /// </summary>
 public void Dispose()
 {
     if (mThread != null)
     {
         mThread.Dispose();
         mThread = null;
     }
 }
Exemplo n.º 8
0
 public void Reset()
 {
     cancellationTokenSource?.Cancel();
     thread?.Factory?.Run(DeallocFFmpeg);
     thread?.Join();
     thread = null;
     buffer = null;
 }
Exemplo n.º 9
0
 public void Join_StopsTask()
 {
     Test.Async(async() =>
     {
         var context = new AsyncContextThread();
         var thread  = await context.Factory.Run(() => Thread.CurrentThread);
         await context.JoinAsync();
     });
 }
Exemplo n.º 10
0
        public static async Task <T> RunAsync <T>(Func <T> func)
        {
            using (var thread = new AsyncContextThread())
            {
                var result = await thread.Factory.Run(() => { return(func()); });

                return(result);
            }
        }
        private async Task StartMessageLoop()
        {
            // Hold on to the current synchronization context
            this.applicationSyncContext = SynchronizationContext.Current;

            // Start the message listener on another thread
            this.messageLoopThread = new AsyncContextThread(true);
            await this.messageLoopThread.Factory.Run(() => this.ListenForMessages());
        }
        public async Task Context_IsCorrectAsyncContext()
        {
            using (var thread = new AsyncContextThread())
            {
                var observedContext = await thread.Factory.Run(() => AsyncContext.Current);

                Assert.Same(observedContext, thread.Context);
            }
        }
        private async Task StartMessageLoop()
        {
            // Hold on to the current synchronization context
            this.applicationSyncContext = SynchronizationContext.Current;

            // Start the message listener on another thread
            this.messageLoopThread = new AsyncContextThread(true);
            await this.messageLoopThread.Factory.Run(() => this.ListenForMessages());
        }
        public async Task AsyncContextThread_IsAnIndependentThread()
        {
            var testThread    = Thread.CurrentThread.ManagedThreadId;
            var thread        = new AsyncContextThread();
            var contextThread = await thread.Factory.Run(() => Thread.CurrentThread.ManagedThreadId);

            Assert.NotEqual(testThread, contextThread);
            await thread.JoinAsync();
        }
Exemplo n.º 15
0
        public async Task Context_IsCorrectAsyncContext()
        {
            using (AsyncContextThread thread = new AsyncContextThread())
            {
                AsyncContext observedContext = await thread.Factory.Run(() => AsyncContext.Current).ConfigureAwait(false);

                Assert.Same(observedContext, thread.Context);
            }
        }
Exemplo n.º 16
0
        public async Task AsyncContextThread_IsAnIndependentThread()
        {
            int testThread            = Thread.CurrentThread.ManagedThreadId;
            AsyncContextThread thread = new AsyncContextThread();
            int contextThread         = await thread.Factory.Run(() => Thread.CurrentThread.ManagedThreadId).ConfigureAwait(false);

            Assert.NotEqual(testThread, contextThread);
            await thread.JoinAsync().ConfigureAwait(false);
        }
 public void Start()
 {
     // Start the main message loop thread.  The Task is
     // not explicitly awaited because it is running on
     // an independent background thread.
     this.messageLoopThread = new AsyncContextThread("Message Dispatcher");
     this.messageLoopThread
     .Run(() => this.ListenForMessages(this.messageLoopCancellationToken.Token))
     .ContinueWith(this.OnListenTaskCompleted);
 }
Exemplo n.º 18
0
        public async Task SynchronizationContext_Send_ExecutesSynchronously()
        {
            using (AsyncContextThread thread = new AsyncContextThread())
            {
                SynchronizationContext synchronizationContext = await thread.Factory.Run(() => SynchronizationContext.Current).ConfigureAwait(false);

                int value = 0;
                synchronizationContext.Send(_ => value = 13, null);
                Assert.Equal(13, value);
            }
        }
Exemplo n.º 19
0
 public void Context_IsCorrectAsyncContext()
 {
     Test.Async(async() =>
     {
         using (var thread = new AsyncContextThread())
         {
             var observedContext = await thread.Factory.Run(() => AsyncContext.Current);
             Assert.AreSame(observedContext, thread.Context);
         }
     });
 }
Exemplo n.º 20
0
        public async Task SynchronizationContext_Send_ExecutesSynchronously()
        {
            using (var thread = new AsyncContextThread())
            {
                var synchronizationContext = await thread.Factory.Run(() => SynchronizationContext.Current);

                int value = 0;
                synchronizationContext.Send(_ => { value = 13; }, null);
                Assert.Equal(13, value);
            }
        }
Exemplo n.º 21
0
            internal static Task <INotifier> StartAsync(NotifierConfiguration config)
            {
                Directory.CreateDirectory(config.WorkingDirectory);

                var thread = new AsyncContextThread();

                return(thread.Factory.Run(() =>
                {
                    var notifier = new Impl(config, thread);
                    return notifier._start.Task;
                }));
            }
Exemplo n.º 22
0
        public PlayerServiceProxy()
        {
            playerThread = new AsyncContextThread();

            // Create proxy object from within playerThread. This should assure valid
            // SynchronizationContext.Current, separate of caller SynchronizationContext.
            // proxied is "set twice" to keep playerThread and caller with current proxied object
            proxied = playerThread.Factory.StartNew(() =>
            {
                proxied = new T();
                return(proxied);
            }).WaitAndUnwrapException();
        }
Exemplo n.º 23
0
        /// <summary>
        /// Runs the given <see cref="AsyncServiceBase"/> service interactively
        /// </summary>
        /// <param name="service">The <see cref="AsyncServiceBase"/> service to run.</param>
        /// <param name="args">Commandline arguments passed to the service.</param>
        internal static void Run(this AsyncServiceBase service, string[] args)
        {
            if (!Environment.UserInteractive)
            {
                throw new NotSupportedException("Not running in UserInteractive mode.");
            }

            var thread = new AsyncContextThread();
            var task   = thread.Factory.Run(() => RunAsync(service, args));

            task.Wait();
            thread.Join();
        }
        public async Task AsyncDelegate_ResumesOnSameThread()
        {
            var thread = new AsyncContextThread();
            int contextThread = -1, resumeThread = -1;
            await thread.Factory.Run(async() =>
            {
                contextThread = Thread.CurrentThread.ManagedThreadId;
                await Task.Yield();
                resumeThread = Thread.CurrentThread.ManagedThreadId;
            });

            Assert.Equal(contextThread, resumeThread);
            await thread.JoinAsync();
        }
Exemplo n.º 25
0
        public async Task SynchronizationContext_Send_ExecutesInlineIfNecessary()
        {
            using (AsyncContextThread thread = new AsyncContextThread())
            {
                int value = 0;
                await thread.Factory.Run(() =>
                {
                    SynchronizationContext.Current.Send(_ => value = 13, null);
                    Assert.Equal(13, value);
                }).ConfigureAwait(false);

                Assert.Equal(13, value);
            }
        }
Exemplo n.º 26
0
        void IBackgroundTask.Run(IBackgroundTaskInstance taskInstance)
        {
            if (this.useSyncronisationContext)
            {
                this.worker = new Nito.AsyncEx.AsyncContextThread();
            }


            this.dereffal = taskInstance.GetDeferral();

            var details = taskInstance.TriggerDetails as AppServiceTriggerDetails;

            details.AppServiceConnection.RequestReceived += this.AppServiceConnection_RequestReceivedAsync;
            details.AppServiceConnection.ServiceClosed   += this.AppServiceConnection_ServiceClosed;;
            taskInstance.Canceled += this.TaskInstance_Canceled;
        }
Exemplo n.º 27
0
 public void SynchronizationContext_Send_ExecutesInlineIfNecessary()
 {
     Test.Async(async() =>
     {
         using (var thread = new AsyncContextThread())
         {
             int value = 0;
             await thread.Factory.Run(() =>
             {
                 SynchronizationContext.Current.Send(_ => { value = 13; }, null);
                 Assert.AreEqual(13, value);
             });
             Assert.AreEqual(13, value);
         }
     });
 }
Exemplo n.º 28
0
            private Impl(NotifierConfiguration config, AsyncContextThread notificationsThread)
            {
                _handlers            = config.Handlers.ToArray();
                _notificationsThread = notificationsThread;
                _gcHandle            = GCHandle.Alloc(this);
                Configuration        = config;
                _start = new TaskCompletionSource <INotifier>();
                try
                {
                    _notifierHandle = NotifierHandle.CreateHandle(_gcHandle, config);
                }
                catch
                {
                    _gcHandle.Free();
                    throw;
                }

                _processor = new CalculationProcessor <string, IntPtr>(CalculateAsync);
            }
Exemplo n.º 29
0
        public EgretConsole(IConsole providedConsole, ILogger <EgretConsole> providedLogger)
        {
            logger = providedLogger;

            console = providedConsole;

            terminal   = console.GetTerminal(preferVirtualTerminal: true, OutputMode.Auto);
            OutputMode = (terminal ?? console).DetectOutputMode();
            formatter  = new TextSpanFormatter();
            renderer   = new ConsoleRenderer(terminal ?? console, resetAfterRender: false);

            formatter.AddFormatter <FileInfo>((f) => f.FullName.StyleValue());
            formatter.AddFormatter <double>((x) => x.ToString("N2").StyleNumber());
            formatter.AddFormatter <int>((x) => x.ToString().StyleNumber());

            var queue = new BlockingCollection <string>();

            // created our own little async event loop so we can run things sequentially
            context = new AsyncContextThread();
        }
Exemplo n.º 30
0
        public void MountNetworkDrive(Guid cloudId, string mountPoint)
        {
            if (mountPoint?.Length != 3 || !mountPoint.EndsWith(@":\", StringComparison.OrdinalIgnoreCase))
            {
                throw new ArgumentException("Mount Point is invalid.");
            }

            if (Globals.Volumes.TryGetValue(cloudId, out var thread) && thread != null)
            {
                UnmountNetworkDrive(cloudId);
            }

            var cloud = Globals.CloudService.PersonalClouds.First(x => new Guid(x.Id) == cloudId);

            var dokanThread = new AsyncContextThread();

            dokanThread.Factory.Run(() => {
                try
                {
                    var disk = new DokanFileSystemAdapter(new PersonalCloudRootFileSystem(cloud, Globals.Loggers.CreateLogger <PersonalCloudRootFileSystem>()));
                    disk.Mount(mountPoint, DokanOptions.EnableNotificationAPI, 5, new DokanyLogger());
                }
                catch (Exception exception)
                {
                    Globals.Loggers.CreateLogger <CloudManagerService>().LogError(exception, "Mount failed.");
                    Globals.Database.SaveSetting(WindowsUserSettings.EnableVolumeMounting, "0");

                    Task.Run(async() => {
                        await Globals.NotificationCenter.InvokeAsync(x => x.OnVolumeIOError(mountPoint, exception))
                        .ConfigureAwait(false);
                        await Task.Delay(TimeSpan.FromSeconds(5)).ConfigureAwait(false);
                        Globals.Volumes.TryRemove(cloudId, out _);
                        dokanThread.Dispose();
                    });
                }
            });

            Globals.Database.SaveSetting(WindowsUserSettings.EnableVolumeMounting, "1");
            Globals.Database.SaveMountPoint(cloudId, mountPoint);
            Globals.Volumes[cloudId] = dokanThread;
        }
        /// <summary>
        /// Initializes the processing pipeline stage (base class specific part).
        /// </summary>
        internal override void OnInitializeBase()
        {
            try
            {
                // set up asynchronous processing
                mAsyncProcessingMessageStack            = new LocklessStack <LocalLogMessage>(mMessageQueueSize, false);
                mTriggerAsyncProcessingEvent            = new AsyncAutoResetEvent(false);
                mAsyncProcessingCancellationTokenSource = new CancellationTokenSource();
                mTerminateProcessingTask = false;
                mAsyncContextThread      = new AsyncContextThread();
                mAsyncProcessingTask     = mAsyncContextThread.Factory.Run(ProcessingTask);

                // Perform pipeline stage specific initialization
                OnInitialize();
            }
            catch (Exception)
            {
                Shutdown();
                throw;
            }
        }