public static void CancelBeforeWait()
        {
            CountdownEvent countdownEvent = new CountdownEvent(2);
            CancellationTokenSource cs = new CancellationTokenSource();
            cs.Cancel();
            CancellationToken ct = cs.Token;

            const int millisec = 100;
            TimeSpan timeSpan = new TimeSpan(100);
            string message = "CancelBeforeWait:  > Cancellation token does not match.";
            EnsureOperationCanceledExceptionThrown(() => countdownEvent.Wait(ct), ct, message);
            EnsureOperationCanceledExceptionThrown(() => countdownEvent.Wait(millisec, ct), ct, message);
            EnsureOperationCanceledExceptionThrown(() => countdownEvent.Wait(timeSpan, ct), ct, message);

            countdownEvent.Dispose();
        }
        public void Cancel時にRegisterで登録したデリゲートが呼ばれる()
        {
            var runner = new SampleTaskRunner.TaskRunner();

            {
                // キャンセルしない場合
                var cts = new CancellationTokenSource();
                var t = new Task<string>(c => Cancelで戻り値が切り替わるコルーチン(10, c, cts.Token));
                t.Start(runner);
                runner.Update(20);

                Assert.IsTrue(t.IsCompleted);
                Assert.AreEqual(CompletedMessage, t.Result);
            }

            {
                // キャンセルする場合
                var cts = new CancellationTokenSource();
                var t = new Task<string>(c => Cancelで戻り値が切り替わるコルーチン(10, c, cts.Token));
                t.Start(runner);
                runner.Update(5);
                cts.Cancel();
                runner.Update(5);

                Assert.IsTrue(t.IsCompleted);
                Assert.AreEqual(CanceledMessage, t.Result);
            }
        }
    static void Main(string[] args)
    {
        var cts = new CancellationTokenSource();
        var ct = cts.Token;

        Task task1 = new Task(() => { Run1(ct); }, ct);

        Task task2 = new Task(Run2);

        try
        {
            task1.Start();
            task2.Start();

            Thread.Sleep(1000);

            cts.Cancel();

            Task.WaitAll(task1, task2);
        }
        catch (AggregateException ex)
        {
            foreach (var e in ex.InnerExceptions)
            {
                Console.WriteLine("\nhi,我是OperationCanceledException:{0}\n", e.Message);
            }

            //task1是否取消
            Console.WriteLine("task1是不是被取消了? {0}", task1.IsCanceled);
            Console.WriteLine("task2是不是被取消了? {0}", task2.IsCanceled);
        }

        Console.Read();
    }
 public OutboxCleaner(OutboxPersister outboxPersister, TimeSpan timeToKeepDeduplicationData, TimeSpan frequencyToRunCleanup)
 {
     cancellationTokenSource = new CancellationTokenSource();
     this.timeToKeepDeduplicationData = timeToKeepDeduplicationData;
     this.frequencyToRunCleanup = frequencyToRunCleanup;
     this.outboxPersister = outboxPersister;
 }
示例#5
0
 public static void Main(String[] args)
 {
     Console.WriteLine("\n-- Cancellation with acknowledgement -------------");
     {
       CancellationTokenSource cts = new CancellationTokenSource();
       CancellationToken token = cts.Token;
       Task task = Task.Run(() => ComputeTaskWithAcknowledgement(token), token);
       Thread.Sleep(0);  // Allow task to be scheduled
       Console.WriteLine(task.Status);   // Running
       cts.Cancel();
       Thread.Sleep(0);
       Console.WriteLine(task.Status);   // Canceled
       try {
     task.Wait();    // Throws AggregateException containing TaskCanceledException
       } catch (Exception exn) {
     Console.WriteLine("Caught " + exn);
       }
       Console.WriteLine(task.Status);   // Canceled
     }
     Console.WriteLine("\n-- Cancellation without acknowledgement ----------");
     {
       CancellationTokenSource cts = new CancellationTokenSource();
       CancellationToken token = cts.Token;
       Task task = Task.Run(() => ComputeTaskWithoutAcknowledgement(token), token);
       Thread.Sleep(0);
       Console.WriteLine(task.Status);   // Running
       cts.Cancel();
       Console.WriteLine(task.Status);   // Running
       task.Wait();
       Console.WriteLine(task.Status);   // RanToCompletion
     }
     Console.WriteLine("\n-- Cancellation before Start ---------------------");
     {
       // Cancel before running
       CancellationTokenSource cts = new CancellationTokenSource();
       CancellationToken token = cts.Token;
       Task task = new Task(delegate { }, token);
       Console.WriteLine(task.Status);   // Created
       cts.Cancel();
       Console.WriteLine(task.Status);   // Canceled
       try {
     task.Start();   // Throws InvalidOperationException
       } catch (Exception exn) {
     Console.WriteLine("Caught " + exn);
       }
       Console.WriteLine(task.Status);   // Canceled
     }
     Console.WriteLine("\n-- Completing before cancellation ----------------");
     {
       CancellationTokenSource cts = new CancellationTokenSource();
       CancellationToken token = cts.Token;
       Task task = new Task(delegate { }, token);
       Console.WriteLine(task.Status);   // Created
       task.Start();
       Thread.Sleep(0);  // Allow task to be scheduled
       Console.WriteLine(task.Status);   // RanToCompletion
       cts.Cancel();
       Console.WriteLine(task.Status);   // RanToCompletion
     }
 }
示例#6
0
    static void Main() {
        
        CancellationTokenSource cts = new CancellationTokenSource();
        CancellationToken token = cts.Token;
        
        Task job = Task.Factory.StartNew(() => {
            for (int i = 0; i < 8; ++i) {
                Console.WriteLine("STEP #{0}", i);
                Thread.Sleep(1000);
                token.ThrowIfCancellationRequested();
            }
            Console.WriteLine("DONE");
        }, token);

        //Thread.Sleep(3500);
        //cts.Cancel();
        cts.CancelAfter(3500);
        Console.WriteLine("(cancellation requested)");

        try {
            job.Wait();
        } catch (Exception) {
            Console.WriteLine("(exception caught)");
        }
        
        Console.WriteLine("FINISHED IN STATE : {0}", job.Status);
    }
        public void Start(IRequestObject requestObject)
        {
            if (requestObject == null)
                return;

            if (IsBusy)
                return;

            _cancellationTokenSource = new CancellationTokenSource();
            _isBusy = true;

            this._requestObject = requestObject;

            var token = _cancellationTokenSource.Token;
            Task.Run(() =>
            {
                while (!token.IsCancellationRequested)
                {
                    var now = DateTime.Now;
                    if (this._requestObject.CanCreateRequst && now >= NextRequestTme)
                    {
                        NextRequestTme = now.AddSeconds(IntervalSeconds);
                        HandleRequestAsync();
                    }
                    System.Threading.Thread.Sleep(500);
                }

                _isBusy = false;
            }, _cancellationTokenSource.Token);

        }
    /// <summary>
    /// Creates an instance of the test class for the given test case. Sends the <see cref="ITestClassConstructionStarting"/>
    /// and <see cref="ITestClassConstructionFinished"/> messages as appropriate.
    /// </summary>
    /// <param name="testCase">The test case</param>
    /// <param name="testClassType">The type of the test class</param>
    /// <param name="constructorArguments">The constructor arguments for the test class</param>
    /// <param name="displayName">The display name of the test case</param>
    /// <param name="messageBus">The message bus used to send the test messages</param>
    /// <param name="timer">The timer used to measure the time taken for construction</param>
    /// <param name="cancellationTokenSource">The cancellation token source</param>
    /// <returns></returns>
    public static object CreateTestClass(this ITestCase testCase,
                                         Type testClassType,
                                         object[] constructorArguments,
                                         string displayName,
                                         IMessageBus messageBus,
                                         ExecutionTimer timer,
                                         CancellationTokenSource cancellationTokenSource)
    {
        object testClass = null;

        if (!messageBus.QueueMessage(new TestClassConstructionStarting(testCase, displayName)))
            cancellationTokenSource.Cancel();

        try
        {
            if (!cancellationTokenSource.IsCancellationRequested)
                timer.Aggregate(() => testClass = Activator.CreateInstance(testClassType, constructorArguments));
        }
        finally
        {
            if (!messageBus.QueueMessage(new TestClassConstructionFinished(testCase, displayName)))
                cancellationTokenSource.Cancel();
        }

        return testClass;
    }
示例#9
0
        public void TestCancel()
        {
            using (var waitHandle = new ManualResetEvent(false))
            {
                // Monitor for a cancellation exception
                var task = new WaitTask("Test task", waitHandle);
                bool exceptionThrown = false;
                var cancellationTokenSource = new CancellationTokenSource();
                var waitThread = new Thread(() =>
                {
                    try
                    {
                        task.Run(cancellationTokenSource.Token);
                    }
                    catch (OperationCanceledException)
                    {
                        exceptionThrown = true;
                    }
                });

                // Start and then cancel the download
                waitThread.Start();
                Thread.Sleep(100);
                cancellationTokenSource.Cancel();
                waitThread.Join();

                exceptionThrown.Should().BeTrue(because: task.State.ToString());
            }
        }
示例#10
0
    static int Main(string[] args)
    {
        SemaphoreSlim s = new SemaphoreSlim(initialCount: 1);

        var cts = new CancellationTokenSource();
        s.Wait();
        var t = s.WaitAsync(cts.Token);
        s.Release();
        cts.Cancel();


        if (t.Status != TaskStatus.Canceled && s.CurrentCount == 0)
        {
            Console.WriteLine("PASS");
            return 100;
        }
        else
        {
            Console.WriteLine("FAIL");
            Console.WriteLine("Expected task status to not be Canceled and s.CurrentCount == 0");
            Console.WriteLine("Actual: Task: " + t.Status + "; CurrentCount: " + s.CurrentCount);
            return 101;
        }


    }
示例#11
0
    public static void Main(){

        CancellationTokenSource cancelTokenSrc = new CancellationTokenSource();
        
        Task<Int32> t = new Task<Int32>( 
            () => { return Sum(100000000, cancelTokenSrc.Token);},
            cancelTokenSrc.Token);       
        
        t.Start();
        
        cancelTokenSrc.Cancel();
        
        Thread.Sleep(1000);
        
        try{
            Console.WriteLine("Waiting...............");
            t.Wait(); 
        }catch(AggregateException ex){        
            ex.Handle(x=> { Console.WriteLine(x.ToString()); return true;});
        } 
        try{
            Console.WriteLine("Extracting Result");
            Console.WriteLine("The Sum is: " + t.Result); // An Int32 value            
        }catch(AggregateException ex){        
            ex.Handle(x=> { Console.WriteLine(x.ToString()); return true;});
        }
    }
示例#12
0
 public CancellationToken(bool canceled)
     : this()
 {
     initialized = true;
     canBeCanceled = canceled;
     // This is correctly set later if token originates from a Source
     source = canceled ? CancellationTokenSource.CanceledSource : CancellationTokenSource.NoneSource;
 }
示例#13
0
 public FactDiscovererTests()
 {
     aggregator = new ExceptionAggregator();
     cancellationTokenSource = new CancellationTokenSource();
     factAttribute = Mocks.FactAttribute();
     messageBus = new SpyMessageBus();
     options = TestFrameworkOptions.ForDiscovery();
 }
示例#14
0
 private static void FireReconnected(IConnection connection,
     CancellationTokenSource reconnectTokenSource,
     ref int reconnectedFired)
 {
     if (!reconnectTokenSource.IsCancellationRequested
         && Interlocked.Exchange(ref reconnectedFired, 1) == 0)
         connection.OnReconnected();
 }
示例#15
0
        public void Precancellation()
        {
            IReadableChannel<int> c = Channel.CreateFromTask(Task.FromResult(42));

            var cts = new CancellationTokenSource();
            cts.Cancel();

            AssertSynchronouslyCanceled(c.WaitToReadAsync(cts.Token), cts.Token);
            AssertSynchronouslyCanceled(c.ReadAsync(cts.Token).AsTask(), cts.Token);
        }
示例#16
0
        public void doStuff(string exampleString)
        {
            cancelSource = new CancellationTokenSource();
            cancelToken = cancelSource.Token;

            var decRep = new Progress<decimal>((decCount) =>
            {
                if (PctChangedEvent != null) PctChangedEvent(decCount);
            });
            Task.Run(() => { doStuffTask(exampleString, decRep, cancelToken); });
        }
        public async Task Cancel_UnpartneredWrite_ThrowsCancellationException()
        {
            IChannel<int> c = Channel.CreateUnbuffered<int>();
            var cts = new CancellationTokenSource();

            Task w = c.WriteAsync(42, cts.Token);
            Assert.False(w.IsCompleted);

            cts.Cancel();
            await AssertCanceled(w, cts.Token);
        }
        public async Task Cancel_UnpartneredRead_ThrowsCancellationException()
        {
            IChannel<int> c = Channel.CreateUnbuffered<int>();
            var cts = new CancellationTokenSource();

            Task r = c.ReadAsync(cts.Token).AsTask();
            Assert.False(r.IsCompleted);

            cts.Cancel();
            await AssertCanceled(r, cts.Token);
        }
    private IRunIntent CreateRunIntent (TaskExecutionNode node)
    {
      var configuration = TaskExecutor.Configuration;

      var runTask = (RunTask) node.RemoteTask;
      var runIntent = RunIntent.Create(configuration.SeparateAppDomain, configuration.ShadowCopy, runTask.VisualStudioProcessId);
      _cancellationTokenSource = runIntent.CancellationTokenSource;

      node.Children.Select(CreateIntent).ForEach(runIntent.AddIntent);

      return runIntent;
    }
    public FullDuplexStreamTests()
    {
        var tuple = FullDuplexStream.CreateStreams();
        Assert.NotNull(tuple);
        Assert.NotNull(tuple.Item1);
        Assert.NotNull(tuple.Item2);

        this.stream1 = tuple.Item1;
        this.stream2 = tuple.Item2;

        TimeSpan timeout = Debugger.IsAttached ? Timeout.InfiniteTimeSpan : TestTimeout;
        this.testCancellationSource = new CancellationTokenSource(timeout);
    }
示例#21
0
 public void Start()
 {
     lock (_taskSyncLocker)
     {
         if (Interlocked.CompareExchange(ref _running, 1, 0) == 0)
         {
             _taskCancellation = new CancellationTokenSource();
             Task task = Task.Factory.StartNew(_taskAction, _taskCancellation.Token,
                 TaskCreationOptions.LongRunning, TaskScheduler.Default).
                 ContinueWith(t => { Interlocked.Exchange(ref _running, 0); });
             Interlocked.Exchange(ref _task, task);
         }
     }
 }
示例#22
0
        public static async Task TimeoutAfter(this Task task, int millisecondsTimeout)
        {
            var cts = new CancellationTokenSource();

            if (task == await Task.WhenAny(task, Task.Delay(millisecondsTimeout, cts.Token)))
            {
                cts.Cancel();
                await task;
            }
            else
            {
                throw new TimeoutException();
            }
        }
    public static void BeforeAfterTestAttributesComeFromBothTestClassAndTestMethod()
    {
        var testCase = Mocks.XunitTestCase<ClassUnderTest>("Passing");
        var messageBus = Substitute.For<IMessageBus>();
        var aggregator = new ExceptionAggregator();
        var tokenSource = new CancellationTokenSource();

        var runner = new XunitTestCaseRunner(testCase, "Display Name", "Skip Reason", new object[0], new object[0], messageBus, aggregator, tokenSource);

        Assert.Collection(runner.BeforeAfterAttributes,
            attr => Assert.IsType<BeforeAfterOnClass>(attr),
            attr => Assert.IsType<BeforeAfterOnMethod>(attr)
        );
    }
        public static void CancelBeforeWait()
        {
            SemaphoreSlim semaphoreSlim = new SemaphoreSlim(2);

            CancellationTokenSource cs = new CancellationTokenSource();
            cs.Cancel();
            CancellationToken ct = cs.Token;

            const int millisec = 100;
            TimeSpan timeSpan = new TimeSpan(100);
            EnsureOperationCanceledExceptionThrown(() => semaphoreSlim.Wait(ct), ct, "CancelBeforeWait:  An OCE should have been thrown.");
            EnsureOperationCanceledExceptionThrown(() => semaphoreSlim.Wait(millisec, ct), ct, "CancelBeforeWait:  An OCE should have been thrown.");
            EnsureOperationCanceledExceptionThrown(() => semaphoreSlim.Wait(timeSpan, ct), ct, "CancelBeforeWait:  An OCE should have been thrown.");
            semaphoreSlim.Dispose();
        }
示例#25
0
        public static void BarrierCancellationTestsCancelAfterWait()
        {
            CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
            CancellationToken cancellationToken = cancellationTokenSource.Token;

            const int numberParticipants = 3;
            Barrier barrier = new Barrier(numberParticipants);

            Task.Run(() => cancellationTokenSource.Cancel());

            //Test that backout occurred.
            Assert.Equal(numberParticipants, barrier.ParticipantsRemaining);

            // the token should not have any listeners.
            // currently we don't expose this.. but it was verified manually
        }
示例#26
0
    public static void Main(){
        Task parent = new Task(() => 
	    {
                var cts = new CancellationTokenSource ();
                var tf  = new TaskFactory<Int32> (cts.Token, 
						  TaskCreationOptions.AttachedToParent,
                                                  TaskContinuationOptions.ExecuteSynchronously, 
						  TaskScheduler.Default);

                // This task creates and starts 3 child tasks
                var childTasks = new[] {
                    tf.StartNew(() => Sum(cts.Token, 10000)),
                    tf.StartNew(() => Sum(cts.Token, 20000)),
                    tf.StartNew(() => Sum(cts.Token, Int32.MaxValue))  // Too big, throws OverflowException
                };

                // If any of the child tasks throw, cancel the rest of them
                for (Int32 task = 0; task < childTasks.Length; task++)
                    childTasks[task].ContinueWith (t => cts.Cancel(), TaskContinuationOptions.OnlyOnFaulted);

                // When all children are done, get the maximum value returned from the
                // non-faulting/canceled tasks. Then pass the maximum value to another
                // task that displays the maximum result
                tf.ContinueWhenAll (childTasks, completedTasks => completedTasks.Where(t => t.Status == TaskStatus.RanToCompletion).Max(t => t.Result), 
                                    CancellationToken.None)
                .ContinueWith(t =>Console.WriteLine("The maximum is: " + t.Result),
                              TaskContinuationOptions.ExecuteSynchronously);
            });

        // When the children are done, show any unhandled exceptions too
        parent.ContinueWith(p => {
                // I put all this text in a StringBuilder and call Console.WriteLine just once
                // because this task could execute concurrently with the task above & I don't
                // want the tasks' output interspersed
                StringBuilder sb = new StringBuilder(
                    "The following exception(s) occurred:" + Environment.NewLine);

                foreach (var e in p.Exception.Flatten().InnerExceptions)
                    sb.AppendLine("   "+ e.GetType().ToString());
                Console.WriteLine(sb.ToString());
            }, TaskContinuationOptions.OnlyOnFaulted);

        // Start the parent Task so it can start its children
        parent.Start();
        Thread.Sleep(1000);
    }
示例#27
0
        /// <summary>
        /// Creates a new task tracking dialog.
        /// </summary>
        /// <param name="task">The trackable task to execute and display.</param>
        /// <param name="credentialProvider">Object used to retrieve credentials for specific <see cref="Uri"/>s on demand; can be <c>null</c>.</param>
        /// <param name="cancellationTokenSource">Used to signal if the user pressed the Cancel button.</param>
        public TaskRunDialog([NotNull] ITask task, [CanBeNull] ICredentialProvider credentialProvider, CancellationTokenSource cancellationTokenSource)
        {
            #region Sanity checks
            if (task == null) throw new ArgumentNullException(nameof(task));
            #endregion

            InitializeComponent();

            buttonCancel.Text = Resources.Cancel;
            buttonCancel.Enabled = task.CanCancel;
            Text = task.Name;

            _task = task;
            _taskThread = new Thread(RunTask);
            _cancellationTokenSource = cancellationTokenSource;
            _credentialProvider = credentialProvider;
        }
        public static void CancelBeforeWait()
        {
            ManualResetEventSlim mres = new ManualResetEventSlim();
            CancellationTokenSource cs = new CancellationTokenSource();
            cs.Cancel();
            CancellationToken ct = cs.Token;

            const int millisec = 100;
            TimeSpan timeSpan = new TimeSpan(100);

            EnsureOperationCanceledExceptionThrown(
               () => mres.Wait(ct), ct, "CancelBeforeWait:  An OCE should have been thrown.");
            EnsureOperationCanceledExceptionThrown(
               () => mres.Wait(millisec, ct), ct, "CancelBeforeWait:  An OCE should have been thrown.");
            EnsureOperationCanceledExceptionThrown(
               () => mres.Wait(timeSpan, ct), ct, "CancelBeforeWait:  An OCE should have been thrown.");
            mres.Dispose();
        }
    public void Start(PushRuntimeSettings limitations)
    {
        runningReceiveTasks = new ConcurrentDictionary<Task, Task>();
        concurrencyLimiter = new SemaphoreSlim(limitations.MaxConcurrency);
        cancellationTokenSource = new CancellationTokenSource();

        cancellationToken = cancellationTokenSource.Token;

        if (purgeOnStartup)
        {
            Directory.Delete(path, true);
            Directory.CreateDirectory(path);
        }

        messagePumpTask = Task.Factory
            .StartNew(ProcessMessages, CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default)
            .Unwrap();
    }
示例#30
0
        public TaskRunDialog([NotNull] ITask task, ICredentialProvider credentialProvider, CancellationTokenSource cancellationTokenSource, [CanBeNull] Widget parent = null)
        {
            #region Sanity checks
            if (task == null) throw new ArgumentNullException(nameof(task));
            #endregion

            Parent = parent;
            // ReSharper disable once DoNotCallOverridableMethodsInConstructor
            Build();

            Title = task.Name;
            buttonCancel.Sensitive = task.CanCancel;

            _task = task;
            _taskThread = new Thread(RunTask);
            _cancellationTokenSource = cancellationTokenSource;
            _credentialProvider = credentialProvider;
        }
示例#31
0
        public async Task <int> RunAsync(string pipeIn, string pipeOut)
        {
            // Validate args.
            ArgUtil.NotNullOrEmpty(pipeIn, nameof(pipeIn));
            ArgUtil.NotNullOrEmpty(pipeOut, nameof(pipeOut));
            var agentWebProxy    = HostContext.GetService <IVstsAgentWebProxy>();
            var agentCertManager = HostContext.GetService <IAgentCertificateManager>();

            VssUtil.InitializeVssClientSettings(HostContext.UserAgent, agentWebProxy.WebProxy, agentCertManager.VssClientCertificateManager);

            var jobRunner = HostContext.CreateService <IJobRunner>();

            using (var channel = HostContext.CreateService <IProcessChannel>())
                using (var jobRequestCancellationToken = CancellationTokenSource.CreateLinkedTokenSource(HostContext.AgentShutdownToken))
                    using (var channelTokenSource = new CancellationTokenSource())
                    {
                        // Start the channel.
                        channel.StartClient(pipeIn, pipeOut);

                        // Wait for up to 30 seconds for a message from the channel.
                        HostContext.WritePerfCounter("WorkerWaitingForJobMessage");
                        Trace.Info("Waiting to receive the job message from the channel.");
                        WorkerMessage channelMessage;
                        using (var csChannelMessage = new CancellationTokenSource(_workerStartTimeout))
                        {
                            channelMessage = await channel.ReceiveAsync(csChannelMessage.Token);
                        }

                        // Deserialize the job message.
                        Trace.Info("Message received.");
                        ArgUtil.Equal(MessageType.NewJobRequest, channelMessage.MessageType, nameof(channelMessage.MessageType));
                        ArgUtil.NotNullOrEmpty(channelMessage.Body, nameof(channelMessage.Body));
                        var jobMessage = JsonUtility.FromString <Pipelines.AgentJobRequestMessage>(channelMessage.Body);
                        ArgUtil.NotNull(jobMessage, nameof(jobMessage));
                        HostContext.WritePerfCounter($"WorkerJobMessageReceived_{jobMessage.RequestId.ToString()}");

                        // Initialize the secret masker and set the thread culture.
                        InitializeSecretMasker(jobMessage);
                        SetCulture(jobMessage);

                        // Start the job.
                        Trace.Info($"Job message:{Environment.NewLine} {StringUtil.ConvertToJson(WorkerUtilities.ScrubPiiData(jobMessage))}");
                        Task <TaskResult> jobRunnerTask = jobRunner.RunAsync(jobMessage, jobRequestCancellationToken.Token);

                        // Start listening for a cancel message from the channel.
                        Trace.Info("Listening for cancel message from the channel.");
                        Task <WorkerMessage> channelTask = channel.ReceiveAsync(channelTokenSource.Token);

                        // Wait for one of the tasks to complete.
                        Trace.Info("Waiting for the job to complete or for a cancel message from the channel.");
                        Task.WaitAny(jobRunnerTask, channelTask);

                        // Handle if the job completed.
                        if (jobRunnerTask.IsCompleted)
                        {
                            Trace.Info("Job completed.");
                            channelTokenSource.Cancel(); // Cancel waiting for a message from the channel.
                            return(TaskResultUtil.TranslateToReturnCode(await jobRunnerTask));
                        }

                        // Otherwise a cancel message was received from the channel.
                        Trace.Info("Cancellation/Shutdown message received.");
                        channelMessage = await channelTask;
                        switch (channelMessage.MessageType)
                        {
                        case MessageType.CancelRequest:
                            jobRequestCancellationToken.Cancel(); // Expire the host cancellation token.
                            break;

                        case MessageType.AgentShutdown:
                            HostContext.ShutdownAgent(ShutdownReason.UserCancelled);
                            break;

                        case MessageType.OperatingSystemShutdown:
                            HostContext.ShutdownAgent(ShutdownReason.OperatingSystemShutdown);
                            break;

                        default:
                            throw new ArgumentOutOfRangeException(nameof(channelMessage.MessageType), channelMessage.MessageType, nameof(channelMessage.MessageType));
                        }

                        // Await the job.
                        return(TaskResultUtil.TranslateToReturnCode(await jobRunnerTask));
                    }
        }
示例#32
0
 public ProcessoThread(int tempo)
 {
     this.Tempo    = tempo;
     this.ShutDown = new CancellationTokenSource();
 }
示例#33
0
        public async Task ProcessSocketAsync(WebSocket socket)
        {
            // Begin sending and receiving. Receiving must be started first because ExecuteAsync enables SendAsync.
            var receiving = StartReceiving(socket);
            var sending = StartSending(socket);

            // Wait for send or receive to complete
            var trigger = await Task.WhenAny(receiving, sending);

            if (trigger == receiving)
            {
                Log.WaitingForSend(_logger);

                // We're waiting for the application to finish and there are 2 things it could be doing
                // 1. Waiting for application data
                // 2. Waiting for a websocket send to complete

                // Cancel the application so that ReadAsync yields
                _application.Input.CancelPendingRead();

                using (var delayCts = new CancellationTokenSource())
                {
                    var resultTask = await Task.WhenAny(sending, Task.Delay(_options.CloseTimeout, delayCts.Token));

                    if (resultTask != sending)
                    {
                        // We timed out so now we're in ungraceful shutdown mode
                        Log.CloseTimedOut(_logger);

                        // Abort the websocket if we're stuck in a pending send to the client
                        _aborted = true;

                        socket.Abort();
                    }
                    else
                    {
                        delayCts.Cancel();
                    }
                }
            }
            else
            {
                Log.WaitingForClose(_logger);

                // We're waiting on the websocket to close and there are 2 things it could be doing
                // 1. Waiting for websocket data
                // 2. Waiting on a flush to complete (backpressure being applied)

                using (var delayCts = new CancellationTokenSource())
                {
                    var resultTask = await Task.WhenAny(receiving, Task.Delay(_options.CloseTimeout, delayCts.Token));

                    if (resultTask != receiving)
                    {
                        // Abort the websocket if we're stuck in a pending receive from the client
                        _aborted = true;

                        socket.Abort();

                        // Cancel any pending flush so that we can quit
                        _application.Output.CancelPendingFlush();
                    }
                    else
                    {
                        delayCts.Cancel();
                    }
                }
            }
        }
示例#34
0
        public async Task HandleConcurrentUpdates(int taskMultiplier)
        {
            // 1/6 ratio of shipment to purchaser tasks gives =>
            // 1 shipment task x 10 seconds / ~50 ms x 25 items = ~5000 items added
            // 6 purchaser tasks x 10 seconds / ~25 ms x 2.5 items = ~ 6000 items attempted to be purchased
            // expecting some lost and diminished sales with worst case scenario around 20%
            const int shipmentToPurchaseMultiplier = 6;

            var hipsterInventory = new ConcurrentDictionary <ItemType, int>();

            var shipments          = new ConcurrentQueue <Shipment>();
            var attemptedPurchases = new ConcurrentQueue <AttemptedPurchase>();
            var tasks = new List <Task>();

            var random = new Random();

            // cancel all tasks after 10 seconds
            var cts = new CancellationTokenSource(TimeSpan.FromSeconds(10));

            // receiving hipster merch shipments
            async Task ShipmentLoop()
            {
                // loop until canceled
                while (true)
                {
                    // get a random item and quantity (10-40) in each shipment
                    var item             = (ItemType)random.Next(0, 5);
                    var shipmentQuantity = random.Next(10, 41);

                    // update inventory
                    hipsterInventory.AddOrUpdate(item, shipmentQuantity, (key, existing) => existing + shipmentQuantity);

                    // create shipment record
                    shipments.Enqueue(new Shipment {
                        Item = item, Quantity = shipmentQuantity
                    });

                    // wait a bit before the next shipment
                    await Task.Delay(random.Next(0, 100), cts.Token);
                }
            }

            // customers buy our hipster merch
            async Task CustomerLoop()
            {
                // delay purchases for 100 milliseconds so we can build up some inventory
                await Task.Delay(TimeSpan.FromMilliseconds(100));

                // loop until canceled
                while (true)
                {
                    // random item and desired quantity (1-4) to purchase
                    var item            = (ItemType)random.Next(0, 5);
                    var desiredQuantity = random.Next(1, 5);

                    var receivedQuantity = -1;

                    // update inventory after purchase
                    hipsterInventory.AddOrUpdate(item,
                                                 // key did not exist, create it with a zero value and set received quantity to zero
                                                 (key) =>
                    {
                        // set closure variable for later consumption
                        receivedQuantity = 0;
                        return(0);
                    },
                                                 // key exists, update using desired quantity
                                                 (key, existing) =>
                    {
                        // set closure variable for later consumption
                        // how many can we receive? => minimum of desired and existing
                        receivedQuantity = Math.Min(existing, desiredQuantity);
                        return(existing - receivedQuantity);
                    });

                    // create purchase record
                    attemptedPurchases.Enqueue(new AttemptedPurchase {
                        Item = item, DesiredQuantity = desiredQuantity, ReceivedQuantity = receivedQuantity
                    });

                    // wait a bit before the next purchase
                    await Task.Delay(random.Next(0, 50), cts.Token);
                }
            }

            // spin up shipments
            for (var i = 0; i < taskMultiplier; ++i)
            {
                tasks.Add(Task.Run(ShipmentLoop, cts.Token));
            }

            // spin up purchasers
            for (var i = 0; i < taskMultiplier * shipmentToPurchaseMultiplier; ++i)
            {
                tasks.Add(Task.Run(CustomerLoop, cts.Token));
            }

            // wait for everything to complete
            await Assert.ThrowsAnyAsync <OperationCanceledException>(() => Task.WhenAll(tasks));

            // total people who at least tried to buy something
            var totalAttemptedPurchases = 0;
            // total people who actually did buy something
            var totalPurchases = 0;
            // we had no inventory of the item they wanted
            var lostSales = 0;
            // we sold them something but couldn't supply all they wanted to buy
            var diminishedSales = 0;
            // total sold items
            var totalSoldItems = 0;
            // total receivedItems
            var totalReceivedItems = 0;
            // total inventory items
            var totalInventory = hipsterInventory.Values.Sum();

            // calculate statistics
            while (attemptedPurchases.TryDequeue(out AttemptedPurchase attemptedPurchase))
            {
                ++totalAttemptedPurchases;

                if (attemptedPurchase.ReceivedQuantity > 0)
                {
                    ++totalPurchases;

                    if (attemptedPurchase.DesiredQuantity != attemptedPurchase.ReceivedQuantity)
                    {
                        ++diminishedSales;
                    }

                    totalSoldItems += attemptedPurchase.ReceivedQuantity;
                }
                else
                {
                    ++lostSales;
                }
            }

            while (shipments.TryDequeue(out var shipment))
            {
                totalReceivedItems += shipment.Quantity;
            }

            var lostOrDiminishedSalesRatio = (lostSales + diminishedSales) / (totalAttemptedPurchases * 1.0d);

            Assert.InRange(lostOrDiminishedSalesRatio, 0.01, 20);
            // make sure we accounted for every item
            Assert.Equal(totalReceivedItems, totalSoldItems + totalInventory);
        }
示例#35
0
        public async Task <bool> SendAsync(string s)
        {
            if (state == ConnectionState.CONNECTED)
            {
                try
                {
                    // Sometimes dataWriter is blocking for an infinite time, so give it a timeout:
                    sendCTS = new CancellationTokenSource(SEND_TIMEOUT_MS);
                    sendCTS.CancelAfter(SEND_TIMEOUT_MS);

                    await WRITE_SEMA.WaitAsync();

                    bool success = true;
                    await Task.Run(async() =>
                    {
                        try
                        {
                            uint l = dataWriter.WriteString(s);

                            // Check if all bytes got actually written to the TCP buffer:
                            if (l < s.Length)
                            {
                                lastConnectionError = new ConnectionError(ConnectionErrorCode.SENDING_FAILED, "Send only " + l + " of " + s.Length + "bytes");
                                Logger.Error(LOGGER_TAG + "Failed to send - " + lastConnectionError.ERROR_MESSAGE + ": " + s);
                                success = false;
                                return;
                            }

                            await dataWriter.StoreAsync();
                            await dataWriter.FlushAsync();
                        }
                        catch (Exception) { }
                    }, sendCTS.Token).ConfigureAwait(false);

                    WRITE_SEMA.Release();

                    if (success)
                    {
                        if (sendCTS.IsCancellationRequested)
                        {
                            lastConnectionError = new ConnectionError(ConnectionErrorCode.SENDING_FAILED, "IsCancellationRequested");
                            Logger.Error(LOGGER_TAG + "Failed to send - " + lastConnectionError.ERROR_MESSAGE + ": " + s);
                            return(false);
                        }
                        Logger.Debug(LOGGER_TAG + "Send to (" + account.serverAddress + "):" + s);
                        return(true);
                    }
                }
                catch (TaskCanceledException e)
                {
                    lastConnectionError = new ConnectionError(ConnectionErrorCode.SENDING_FAILED, "TaskCanceledException");
                    if (Logger.logLevel >= LogLevel.DEBUG)
                    {
                        Logger.Error(LOGGER_TAG + "Failed to send - " + lastConnectionError.ERROR_MESSAGE + ": " + s, e);
                    }
                    else
                    {
                        Logger.Error(LOGGER_TAG + "Failed to send message - " + lastConnectionError.ERROR_MESSAGE + ": " + s);
                    }

                    WRITE_SEMA.Release();
                }
                catch (Exception e)
                {
                    lastConnectionError = new ConnectionError(ConnectionErrorCode.SENDING_FAILED, e.Message);
                    if (Logger.logLevel >= LogLevel.DEBUG)
                    {
                        Logger.Error(LOGGER_TAG + "Failed to send - " + lastConnectionError.ERROR_MESSAGE + ": " + s, e);
                    }
                    else
                    {
                        Logger.Error(LOGGER_TAG + "Failed to send - " + lastConnectionError.ERROR_MESSAGE + ": " + s);
                    }

                    WRITE_SEMA.Release();
                }
            }
            return(false);
        }
示例#36
0
        private void Sync_Click(object sender, RoutedEventArgs e)
        {
            if (_token != null)
            {
                StopSync();
                return;
            }

            Sync.Content = LocalizedStrings.Str2890;

            _token = new CancellationTokenSource();

            Task.Factory.StartNew(() =>
            {
                var securityPaths = new List <string>();

                foreach (var dir in DriveCache.Instance.AllDrives
                         .OfType <LocalMarketDataDrive>()
                         .Select(drive => drive.Path)
                         .Distinct())
                {
                    foreach (var letterDir in InteropHelper.GetDirectories(dir))
                    {
                        if (_token.IsCancellationRequested)
                        {
                            break;
                        }

                        var name = Path.GetFileName(letterDir);

                        if (name == null || name.Length != 1)
                        {
                            continue;
                        }

                        securityPaths.AddRange(InteropHelper.GetDirectories(letterDir));
                    }

                    if (_token.IsCancellationRequested)
                    {
                        break;
                    }
                }

                if (_token.IsCancellationRequested)
                {
                    return;
                }

                var iterCount =
                    securityPaths.Count +                                                                                                // кол-во проходов по директории для создания инструмента
                    DriveCache.Instance.AllDrives.Count() * (((IList <Security>)EntityRegistry.Securities).Count + securityPaths.Count); // кол-во сбросов кэша дат

                this.GuiSync(() => Progress.Maximum = iterCount);

                var logSource = ConfigManager.GetService <LogManager>().Application;

                var securityIdGenerator = new SecurityIdGenerator();

                var securities = EntityRegistry.Securities.ToDictionary(s => s.Id, s => new KeyValuePair <Security, bool>(s, true), StringComparer.InvariantCultureIgnoreCase);

                foreach (var securityPath in securityPaths)
                {
                    if (_token.IsCancellationRequested)
                    {
                        break;
                    }

                    var securityId = Path.GetFileName(securityPath).FolderNameToSecurityId();

                    var isNew = false;

                    var security = securities.TryGetValue(securityId).Key;
                    if (security == null)
                    {
                        var firstDataFile =
                            Directory.EnumerateDirectories(securityPath)
                            .SelectMany(d => Directory.EnumerateFiles(d, "*.bin")
                                        .Concat(Directory.EnumerateFiles(d, "*.csv"))
                                        .OrderBy(f => Path.GetExtension(f).CompareIgnoreCase(".bin") ? 0 : 1))
                            .FirstOrDefault();

                        if (firstDataFile != null)
                        {
                            var id = securityIdGenerator.Split(securityId);

                            decimal priceStep;

                            if (Path.GetExtension(firstDataFile).CompareIgnoreCase(".bin"))
                            {
                                try
                                {
                                    priceStep = File.ReadAllBytes(firstDataFile).Range(6, 16).To <decimal>();
                                }
                                catch (Exception ex)
                                {
                                    throw new InvalidOperationException(LocalizedStrings.Str2929Params.Put(firstDataFile), ex);
                                }
                            }
                            else
                            {
                                priceStep = 0.01m;
                            }

                            security = new Security
                            {
                                Id            = securityId,
                                PriceStep     = priceStep,
                                Name          = id.SecurityCode,
                                Code          = id.SecurityCode,
                                Board         = ExchangeBoard.GetOrCreateBoard(id.BoardCode),
                                ExtensionInfo = new Dictionary <object, object>()
                            };

                            securities.Add(securityId, new KeyValuePair <Security, bool>(security, false));

                            isNew = true;
                        }
                    }

                    this.GuiSync(() =>
                    {
                        Progress.Value++;

                        if (isNew)
                        {
                            Logs.Messages.Add(new LogMessage(logSource, TimeHelper.NowWithOffset, LogLevels.Info, LocalizedStrings.Str2930Params.Put(security)));
                        }
                    });
                }

                EntityRegistry.Securities.AddRange(securities.Values.Where(p => !p.Value).Select(p => p.Key));

                if (_token.IsCancellationRequested)
                {
                    return;
                }

                //var dataTypes = new[]
                //{
                //	Tuple.Create(typeof(ExecutionMessage), (object)ExecutionTypes.Tick),
                //	Tuple.Create(typeof(ExecutionMessage), (object)ExecutionTypes.OrderLog),
                //	Tuple.Create(typeof(ExecutionMessage), (object)ExecutionTypes.Order),
                //	Tuple.Create(typeof(ExecutionMessage), (object)ExecutionTypes.Trade),
                //	Tuple.Create(typeof(QuoteChangeMessage), (object)null),
                //	Tuple.Create(typeof(Level1ChangeMessage), (object)null),
                //	Tuple.Create(typeof(NewsMessage), (object)null)
                //};

                var formats = Enumerator.GetValues <StorageFormats>().ToArray();

                foreach (var drive in DriveCache.Instance.AllDrives)
                {
                    foreach (var secId in drive.AvailableSecurities)
                    {
                        foreach (var format in formats)
                        {
                            foreach (var dataType in drive.GetAvailableDataTypes(secId, format))
                            {
                                if (_token.IsCancellationRequested)
                                {
                                    break;
                                }

                                drive
                                .GetStorageDrive(secId, dataType.MessageType, dataType.Arg, format)
                                .ClearDatesCache();
                            }
                        }

                        if (_token.IsCancellationRequested)
                        {
                            break;
                        }

                        this.GuiSync(() =>
                        {
                            Progress.Value++;
                            Logs.Messages.Add(new LogMessage(logSource, TimeHelper.NowWithOffset, LogLevels.Info,
                                                             LocalizedStrings.Str2931Params.Put(secId, drive.Path)));
                        });
                    }

                    if (_token.IsCancellationRequested)
                    {
                        break;
                    }
                }
            }, _token.Token)
            .ContinueWithExceptionHandling(this, res =>
            {
                Sync.Content   = LocalizedStrings.Str2932;
                Sync.IsEnabled = true;

                Progress.Value = 0;

                _token = null;
            });
        }
示例#37
0
 void CancelTooltip()
 {
     tooltipCancelSrc.Cancel();
     tooltipCancelSrc = new CancellationTokenSource();
 }
示例#38
0
        // TODO: double check and maybe change order of parameters
        public ProcessExecutionResult Execute(string fileName, string inputData, int timeLimit, int memoryLimit, IEnumerable <string> executionArguments = null)
        {
            var result = new ProcessExecutionResult {
                Type = ProcessExecutionResultType.Success
            };
            var workingDirectory = new FileInfo(fileName).DirectoryName;

            using (var restrictedProcess = new RestrictedProcess(fileName, workingDirectory, executionArguments, Math.Max(4096, (inputData.Length * 2) + 4)))
            {
                // Write to standard input using another thread
                restrictedProcess.StandardInput.WriteLineAsync(inputData).ContinueWith(
                    delegate
                {
                    // ReSharper disable once AccessToDisposedClosure
                    if (!restrictedProcess.IsDisposed)
                    {
                        // ReSharper disable once AccessToDisposedClosure
                        restrictedProcess.StandardInput.FlushAsync().ContinueWith(
                            delegate
                        {
                            restrictedProcess.StandardInput.Close();
                        });
                    }
                });

                // Read standard output using another thread to prevent process locking (waiting us to empty the output buffer)
                var processOutputTask = restrictedProcess.StandardOutput.ReadToEndAsync().ContinueWith(
                    x =>
                {
                    result.ReceivedOutput = x.Result;
                });

                // Read standard error using another thread
                var errorOutputTask = restrictedProcess.StandardError.ReadToEndAsync().ContinueWith(
                    x =>
                {
                    result.ErrorOutput = x.Result;
                });

                // Read memory consumption every few milliseconds to determine the peak memory usage of the process
                const int TimeIntervalBetweenTwoMemoryConsumptionRequests = 45;
                var       memoryTaskCancellationToken = new CancellationTokenSource();
                var       memoryTask = Task.Run(
                    () =>
                {
                    while (true)
                    {
                        // ReSharper disable once AccessToDisposedClosure
                        var peakWorkingSetSize = restrictedProcess.PeakWorkingSetSize;

                        result.MemoryUsed = Math.Max(result.MemoryUsed, peakWorkingSetSize);

                        if (memoryTaskCancellationToken.IsCancellationRequested)
                        {
                            return;
                        }

                        Thread.Sleep(TimeIntervalBetweenTwoMemoryConsumptionRequests);
                    }
                },
                    memoryTaskCancellationToken.Token);

                // Start the process
                restrictedProcess.Start(timeLimit, memoryLimit);

                // Wait the process to complete. Kill it after (timeLimit * 1.5) milliseconds if not completed.
                // We are waiting the process for more than defined time and after this we compare the process time with the real time limit.
                var exited = restrictedProcess.WaitForExit((int)(timeLimit * 1.5));
                if (!exited)
                {
                    restrictedProcess.Kill();
                    result.Type = ProcessExecutionResultType.TimeLimit;
                }

                // Close the memory consumption check thread
                memoryTaskCancellationToken.Cancel();
                try
                {
                    // To be sure that memory consumption will be evaluated correctly
                    memoryTask.Wait(TimeIntervalBetweenTwoMemoryConsumptionRequests);
                }
                catch (AggregateException ex)
                {
                    logger.Warn("AggregateException caught.", ex.InnerException);
                }

                // Close the task that gets the process error output
                try
                {
                    errorOutputTask.Wait(100);
                }
                catch (AggregateException ex)
                {
                    logger.Warn("AggregateException caught.", ex.InnerException);
                }

                // Close the task that gets the process output
                try
                {
                    processOutputTask.Wait(100);
                }
                catch (AggregateException ex)
                {
                    logger.Warn("AggregateException caught.", ex.InnerException);
                }

                Debug.Assert(restrictedProcess.HasExited, "Restricted process didn't exit!");

                // Report exit code and total process working time
                result.ExitCode   = restrictedProcess.ExitCode;
                result.TimeWorked = restrictedProcess.ExitTime - restrictedProcess.StartTime;
                result.PrivilegedProcessorTime = restrictedProcess.PrivilegedProcessorTime;
                result.UserProcessorTime       = restrictedProcess.UserProcessorTime;
            }

            if (result.TotalProcessorTime.TotalMilliseconds > timeLimit)
            {
                result.Type = ProcessExecutionResultType.TimeLimit;
            }

            if (!string.IsNullOrEmpty(result.ErrorOutput))
            {
                result.Type = ProcessExecutionResultType.RunTimeError;
            }

            if (result.MemoryUsed > memoryLimit)
            {
                result.Type = ProcessExecutionResultType.MemoryLimit;
            }

            return(result);
        }
示例#39
0
        private static void VerifyLocalDataSlot(LocalDataStoreSlot slot)
        {
            Assert.NotNull(slot);

            var waitForThreadArray      = new Action[2];
            var threadArray             = new Thread[2];
            var barrier                 = new Barrier(threadArray.Length);
            var cancellationTokenSource = new CancellationTokenSource();
            var cancellationToken       = cancellationTokenSource.Token;

            Func <bool> barrierSignalAndWait =
                () =>
            {
                try
                {
                    Assert.True(barrier.SignalAndWait(UnexpectedTimeoutMilliseconds, cancellationToken));
                }
                catch (OperationCanceledException)
                {
                    return(false);
                }
                return(true);
            };

            Action <int> threadMain =
                threadIndex =>
            {
                try
                {
                    Assert.Null(Thread.GetData(slot));
                    if (!barrierSignalAndWait())
                    {
                        return;
                    }

                    if (threadIndex == 0)
                    {
                        Thread.SetData(slot, threadIndex);
                    }
                    if (!barrierSignalAndWait())
                    {
                        return;
                    }

                    if (threadIndex == 0)
                    {
                        Assert.Equal(threadIndex, Thread.GetData(slot));
                    }
                    else
                    {
                        Assert.Null(Thread.GetData(slot));
                    }
                    if (!barrierSignalAndWait())
                    {
                        return;
                    }

                    if (threadIndex != 0)
                    {
                        Thread.SetData(slot, threadIndex);
                    }
                    if (!barrierSignalAndWait())
                    {
                        return;
                    }

                    Assert.Equal(threadIndex, Thread.GetData(slot));
                    if (!barrierSignalAndWait())
                    {
                        return;
                    }
                }
                catch (Exception ex)
                {
                    cancellationTokenSource.Cancel();
                    throw new TargetInvocationException(ex);
                }
            };

            for (int i = 0; i < threadArray.Length; ++i)
            {
                threadArray[i] = ThreadTestHelpers.CreateGuardedThread(out waitForThreadArray[i], () => threadMain(i));
                threadArray[i].IsBackground = true;
                threadArray[i].Start();
            }

            foreach (var waitForThread in waitForThreadArray)
            {
                waitForThread();
            }
        }
 protected override void OnAppearing()
 {
     base.OnAppearing();
     cts = new CancellationTokenSource();
     Task.Run(async() => await placeholderUsersVM.Fetch());
 }
示例#41
0
        /// <summary>Called to run the command. Can throw on error.</summary>
        /// <param name="cancelToken">Is cancellation pending?</param>
        public void Run(CancellationTokenSource cancelToken)
        {
            if (database == null)
                return;

            bool deleteEverything = false;
            if (database.TableExists("_Checkpoints"))
            {
                var checkpointData = new DataView(database.ExecuteQuery("SELECT * FROM [_Checkpoints]"));
                if (checkpointData.Table.Rows.Count == 1)
                    deleteEverything = true;
                else
                {
                    checkpointData.RowFilter = "Name='Current'";
                    if (checkpointData.Count == 1)
                    {
                        int checkId = Convert.ToInt32(checkpointData[0]["ID"], CultureInfo.InvariantCulture);

                        // Delete current data from all tables.
                        foreach (string tableName in database.GetTableNames())
                        {
                            if (!tableName.StartsWith("_") && database.TableExists(tableName))
                                database.ExecuteNonQuery(string.Format("DELETE FROM [{0}] WHERE [CheckpointID]={1}", tableName, checkId));
                        }
                    }
                }
            }
            else
                deleteEverything = true;

            if (deleteEverything)
            {
                // No checkpoint information, so get rid of everything
                // Delete current data from all tables.
                foreach (string tableName in database.GetTableNames())
                {
                    if (!tableName.StartsWith("_"))
                        database.ExecuteNonQuery(string.Format("DELETE FROM [{0}]", tableName));
                }
            }

            // Delete empty tables.
            List<string> tableNamesToDelete = new List<string>();
            bool allTablesEmpty = true;
            foreach (string tableName in database.GetTableNames())
            {
                if (!tableName.StartsWith("_"))
                {
                    if (database.TableIsEmpty(tableName))
                        tableNamesToDelete.Add(tableName);
                    else
                        allTablesEmpty = false;
                }
            }

            // If all data tables were emptied then delete all tables.
            if (allTablesEmpty)
            {
                tableNamesToDelete = database.GetTableNames();
                // remove any database Views created if no tables remain
                foreach (string viewName in database.GetViewNames())
                {
                    database.ExecuteNonQuery(string.Format("DROP VIEW IF EXISTS [{0}]", viewName));
                }
            }

            foreach (string tableName in tableNamesToDelete)
                database.DropTable(tableName);
            if (database is SQLite)
            {
                (database as SQLite).Vacuum();
            }
        }
示例#42
0
        private void OnStartup(object sender, StartupEventArgs e)
        {
            AppDomain.CurrentDomain.UnhandledException += OnUnhandledException;

            RunnerHelper.WaitForPowerToysRunner(PowerToysPID, () =>
            {
                Environment.Exit(0);
            });

            _themeManager = new ThemeManager(this);

            if (!FancyZonesEditorIO.ParseParams().Result)
            {
                FancyZonesEditorIO.ParseCommandLineArguments();
            }

            var parseResult = FancyZonesEditorIO.ParseZoneSettings();

            // 10ms retry loop with 1 second timeout
            if (!parseResult.Result)
            {
                CancellationTokenSource ts = new CancellationTokenSource();
                Task t = Task.Run(() =>
                {
                    while (!parseResult.Result && !ts.IsCancellationRequested)
                    {
                        Task.Delay(10).Wait();
                        parseResult = FancyZonesEditorIO.ParseZoneSettings();
                    }
                });

                try
                {
                    bool result = t.Wait(1000, ts.Token);
                    ts.Cancel();
                }
                catch (OperationCanceledException)
                {
                    ts.Dispose();
                }
            }

            // Error message if parsing failed
            if (!parseResult.Result)
            {
                var sb = new StringBuilder();
                sb.AppendLine();
                sb.AppendLine("## " + ParsingErrorReportTag);
                sb.AppendLine();
                sb.AppendLine(parseResult.Message);
                sb.AppendLine();
                sb.AppendLine(ParsingErrorDataTag);
                sb.AppendLine(parseResult.MalformedData);

                MessageBox.Show(parseResult.Message, FancyZonesEditor.Properties.Resources.Error_Parsing_Zones_Settings_Title, MessageBoxButton.OK);
            }

            MainWindowSettingsModel settings = ((App)Current).MainWindowSettings;

            settings.UpdateSelectedLayoutModel();

            Overlay.Show();
        }
示例#43
0
        private void StartReaderTask()
        {
            // Ensure no other reader task is running:
            StopReaderTask();

            readCTS = new CancellationTokenSource();

            try
            {
                Task.Run(async() =>
                {
                    TCPReadResult readResult   = null;
                    int lastReadingFailedCount = 0;
                    int errorCount             = 0;
                    DateTime lastReadingFailed = DateTime.MinValue;

                    while (state == ConnectionState.CONNECTED && errorCount < 3)
                    {
                        try
                        {
                            readResult = await ReadAsync();
                            // Check if reading failed:
                            switch (readResult.STATE)
                            {
                            case TCPReadState.SUCCESS:
                                lastReadingFailedCount = 0;
                                errorCount             = 0;
                                Logger.Debug(LOGGER_TAG + "Received from (" + account.serverAddress + "):" + readResult.DATA);

                                // Trigger the NewDataReceived event:
                                NewDataReceived?.Invoke(this, new NewDataReceivedEventArgs(readResult.DATA));
                                break;

                            case TCPReadState.FAILURE:
                                if (lastReadingFailedCount++ <= 0)
                                {
                                    lastReadingFailed = DateTime.Now;
                                }

                                // Read 5 empty or null strings in an interval lower than 1 second:
                                double c = DateTime.Now.Subtract(lastReadingFailed).TotalSeconds;
                                if (lastReadingFailedCount > 5 && c < 1)
                                {
                                    lastConnectionError = new ConnectionError(ConnectionErrorCode.READING_LOOP);
                                    errorCount          = int.MaxValue;
                                    continue;
                                }
                                break;

                            case TCPReadState.END_OF_STREAM:
                                Logger.Info(LOGGER_TAG + "Socket closed because received 0-length message from: " + account.serverAddress);
                                await DisconnectAsync();
                                break;
                            }
                        }
                        catch (OperationCanceledException)
                        {
                            lastConnectionError = new ConnectionError(ConnectionErrorCode.READING_CANCELED);
                            errorCount++;
                        }
                        catch (Exception e)
                        {
                            SocketErrorStatus status = SocketErrorStatus.Unknown;
                            if (e is AggregateException aggregateException && aggregateException.InnerException != null)
                            {
                                status = SocketError.GetStatus(e.InnerException.HResult);
                            }
                            else
                            {
                                Exception baseException = e.GetBaseException();
                                if (baseException != null)
                                {
                                    status = SocketError.GetStatus(e.GetBaseException().HResult);
                                }
                                else
                                {
                                    status = SocketError.GetStatus(e.HResult);
                                }
                            }

                            lastConnectionError = new ConnectionError(status, e.Message);
                            switch (status)
                            {
                            // Some kind of connection lost:
                            case SocketErrorStatus.ConnectionTimedOut:
                            case SocketErrorStatus.ConnectionRefused:
                            case SocketErrorStatus.NetworkDroppedConnectionOnReset:
                            case SocketErrorStatus.SoftwareCausedConnectionAbort:
                            case SocketErrorStatus.ConnectionResetByPeer:
                                errorCount = int.MaxValue;
                                break;

                            default:
                                errorCount++;
                                break;
                            }
                        }
示例#44
0
        protected IObservable<string> BtStreamSubscribe(ZmqPubSubEndpointConfig config)
        {
            return Observable.Defer(() => Observable.Create<string>(obs =>
            {
                var tcs = new CancellationTokenSource();

                Task.Factory.StartNew(() =>
                {
                    using(tcs)
                    {
                        while(!tcs.IsCancellationRequested)
                        {
                            try
                            {
                                using(var subSocket = new ZSocket(ZSocketType.SUB))
                                {
                                    //subSocket.Options.ReceiveHighWatermark = 1000;
                                    subSocket.SetupCurveTlsClient(config.SharedEncryptionKey, logger);
                                    subSocket.Connect(config.Url);
                                    subSocket.Subscribe(config.Topic);

                                    logger.Debug($"Subscribed to {config.Url}/{config.Topic}");

                                    while(!tcs.IsCancellationRequested)
                                    {
                                        // string topic;
                                        uint flags;
                                        byte[] data;
                                        // long timestamp;

                                        using (var msg = subSocket.ReceiveMessage())
                                        {
                                            // extract frames
                                            // topic = msg[0].ToString(Encoding.UTF8);
                                            flags = msg[1].ReadUInt32();
                                            data = msg[2].Read();
                                            // timestamp = msg[3].ReadInt64();
                                        }

                                        // TMP FIX
                                        if (flags != 0 && ((flags & 1) == 0))
                                            flags = BitConverter.ToUInt32(BitConverter.GetBytes(flags).ToNewReverseArray());

                                        // compressed
                                        if ((flags & 1) == 1)
                                        {
                                            using(var stm = new MemoryStream(data))
                                            {
                                                using(var stmOut = new MemoryStream())
                                                {
                                                    using(var ds = new DeflateStream(stm, CompressionMode.Decompress))
                                                    {
                                                        ds.CopyTo(stmOut);
                                                    }

                                                    data = stmOut.ToArray();
                                                }
                                            }
                                        }

                                        // convert
                                        var json = Encoding.UTF8.GetString(data);

                                        // publish
                                        obs.OnNext(json);

                                        // telemetry
                                        //messageBus.SendMessage(new TelemetryEvent(clusterConfig.ClusterName ?? poolConfig.PoolName, poolConfig.Id,
                                        //    TelemetryCategory.BtStream, DateTime.UtcNow - DateTimeOffset.FromUnixTimeSeconds(timestamp)));
                                    }
                                }
                            }

                            catch(Exception ex)
                            {
                                logger.Error(ex);
                            }

                            // do not consume all CPU cycles in case of a long lasting error condition
                            Thread.Sleep(1000);
                        }
                    }
                }, tcs.Token, TaskCreationOptions.LongRunning, TaskScheduler.Default);

                return Disposable.Create(() => { tcs.Cancel(); });
            }))
            .Publish()
            .RefCount();
        }
示例#45
0
        public static async Task ManageAdvSend(SettingBussines clsSetting)
        {
            try
            {
                var tokenSource = new CancellationTokenSource();

                SimcardBussines firstSimCardBusiness = null;
                var             list = await SimcardBussines.GetAllAsync();

                list = list.OrderBy(q => q.NextUse).Where(q => q.Status).ToList();
                foreach (var simCard in list)
                {
                    while (!await Utility.PingHost("www.google.com"))
                    {
                        //خطا در برقراری اتصال به اینترنت
                        await Utility.Wait(10);

                        lstMessage.Clear();
                        lstMessage.Add("خطا در برقراری اتصال به اینترنت");
                        Utility.ShowBalloon("لطفا شبکه خود را چک نمایید", lstMessage);
                    }

                    if (simCard.isSendPostToTelegram)
                    {
                        var city = DivarCityBussines.GetAsync(simCard.CityForGetPost ?? Guid.Empty)?.Name ?? "مشهد";
                        var cat1 = AdvCategoryBussines.Get(simCard.DivarPostCat1 ?? Guid.Empty)?.Name ?? "خدمات";
                        var cat2 = AdvCategoryBussines.Get(simCard.DivarPostCat2 ?? Guid.Empty)?.Name ??
                                   "آرایشگری و زیبایی";
                        var cat3   = AdvCategoryBussines.Get(simCard.DivarPostCat3 ?? Guid.Empty)?.Name ?? "";
                        var chatID = simCard.ChannelForSendPost ?? "@Test2_2211201";
                        var divar  = await DivarAdv.GetInstance();

                        await divar.GetPost(simCard.Number, cat1, cat2, cat3
                                            , city, simCard.PostCount ?? 5, chatID, simCard.DescriptionForPost ?? "",
                                            simCard.SMS_Description);
                    }

                    if (simCard.IsSendAdv)
                    {
                        try
                        {
                            //کنترل شماره خروجی
                            if (simCard.Number == 0)
                            {
                                lstMessage.Clear();
                                lstMessage.Add("پر شدن تعداد آگهی در IP");
                                Utility.ShowBalloon("پر شدن تعداد آگهی در " + await Utility.FindGateWay(), lstMessage);
                                continue;
                            }

                            //کنترل تعداد آگهی ارسال شده در هر IP
                            while (clsSetting?.CountAdvInIP <=
                                   AdvertiseLogBussines.GetAllAdvInDayFromIP(await Utility.GetLocalIpAddress()))
                            {
                                await Utility.Wait(20);

                                lstMessage.Clear();
                                lstMessage.Add("پر شدن تعداد آگهی");
                                Utility.ShowBalloon("پر شدن تعداد آگهی در " + await Utility.FindGateWay(), lstMessage);
                                await SendChat(clsSetting, simCard);
                            }

                            firstSimCardBusiness = await SimcardBussines.GetAsync(simCard.Number);

                            if (firstSimCardBusiness is null)
                            {
                                continue;
                            }

                            var lastUse = firstSimCardBusiness.NextUse;
                            var startDayOfCurrentMonthOfDateShToMiladi = DateConvertor.StartDayOfPersianMonth();
                            var startDayOfNextMonthOfDateShToMiladi    = DateConvertor.EndDayOfPersianMonth().AddDays(1);
                            //آمار آگهی های ثبت شده برای سیم کارت در ماه جاری
                            var a1 = await AdvertiseLogBussines.GetAllAsync();

                            a1 = a1.Where(p => p.SimCardNumber == simCard.Number &&
                                          (p.StatusCode ==
                                           StatusCode
                                           .Published ||
                                           p.StatusCode ==
                                           StatusCode
                                           .InPublishQueue ||
                                           p.StatusCode ==
                                           StatusCode
                                           .WaitForPayment) &&
                                          p.DateM >=
                                          startDayOfCurrentMonthOfDateShToMiladi).ToList();

                            var registeredAdvCount = a1.Count;
                            if (registeredAdvCount >= clsSetting?.CountAdvInMounth)
                            {
                                //تاریخ روز اول ماه شمسی بعد را تنظیم می کند چون تا سر ماه بعد دیگر نیازی به این سیم کارت نیست
                                firstSimCardBusiness.NextUse = startDayOfNextMonthOfDateShToMiladi;
                                await firstSimCardBusiness.SaveAsync();

                                lstMessage.Clear();
                                lstMessage.Add(
                                    $"سیمکارت {simCard.Number} به دلیل پر بودن آگهی ها در ماه موفق به ارسال آگهی نشد");
                                Utility.ShowBalloon("عدم ارسال آگهی", lstMessage);
                                await SendChat(clsSetting, simCard);

                                continue;
                            }

                            //آمار آگهی های ثبت شده امروز
                            var currentDate = DateTime.Now.Date;
                            var a2          = await AdvertiseLogBussines.GetAllAsync();

                            a2 = a2.Where(p =>
                                          p.SimCardNumber == simCard.Number &&
                                          (p.StatusCode == StatusCode.Published ||
                                           p.StatusCode == StatusCode.InPublishQueue ||
                                           p.StatusCode == StatusCode.WaitForPayment) &&
                                          p.DateM >= currentDate).ToList();
                            registeredAdvCount = a2.Count;
                            if (registeredAdvCount >= clsSetting?.CountAdvInDay)
                            {
                                //تاریخ فردا رو ست می کند چون تا فردا دیگه نیازی به این سیم کارت نیست
                                firstSimCardBusiness.NextUse = DateTime.Today.AddDays(1);
                                await firstSimCardBusiness.SaveAsync();

                                lstMessage.Clear();
                                lstMessage.Add(
                                    $"سیمکارت {simCard.Number} به دلیل پرپودن آگهی ها در روز موفق به ارسال آگهی نشد");
                                Utility.ShowBalloon("عدم ارسال آگهی", lstMessage);
                                await SendChat(clsSetting, simCard);

                                continue;
                            }

                            var divar = await DivarAdv.GetInstance();

                            await divar.StartRegisterAdv(simCard);

                            simCard.NextUse = DateTime.Now.AddMinutes(30);
                            await simCard.SaveAsync();
                            await Wait(2);
                        }
                        catch (Exception e)
                        {
                        }
                    }
                    if (simCard.IsSendAdvSheypoor)
                    {
                        //کنترل شماره خروجی
                        if (simCard.Number == 0)
                        {
                            lstMessage.Clear();
                            lstMessage.Add("پر شدن تعداد آگهی در IP");
                            Utility.ShowBalloon("پر شدن تعداد آگهی در " + await Utility.FindGateWay(), lstMessage);
                            continue;
                        }

                        //کنترل تعداد آگهی ارسال شده در هر IP
                        while (clsSetting?.CountAdvInIP <=
                               AdvertiseLogBussines.GetAllAdvInDayFromIP(await Utility.GetLocalIpAddress()))
                        {
                            await Utility.Wait(20);

                            lstMessage.Clear();
                            lstMessage.Add("پر شدن تعداد آگهی");
                            Utility.ShowBalloon("پر شدن تعداد آگهی در " + await Utility.FindGateWay(), lstMessage);
                            await SendChat(clsSetting, simCard);
                        }

                        firstSimCardBusiness = await SimcardBussines.GetAsync(simCard.Number);

                        if (firstSimCardBusiness is null)
                        {
                            continue;
                        }

                        var lastUse = firstSimCardBusiness.NextUse;
                        var card1   = simCard.Number;
                        var startDayOfCurrentMonthOfDateShToMiladi = DateConvertor.StartDayOfPersianMonth();
                        var startDayOfNextMonthOfDateShToMiladi    = DateConvertor.EndDayOfPersianMonth().AddDays(1);
                        //آمار آگهی های ثبت شده برای سیم کارت در ماه جاری
                        var a1 = await AdvertiseLogBussines.GetAllAsync();

                        a1 = a1.Where(p => p.SimCardNumber == card1 &&
                                      (p.StatusCode ==
                                       StatusCode
                                       .Published ||
                                       p.StatusCode ==
                                       StatusCode
                                       .InPublishQueue ||
                                       p.StatusCode ==
                                       StatusCode
                                       .WaitForPayment) &&
                                      p.DateM >=
                                      startDayOfCurrentMonthOfDateShToMiladi).ToList();

                        var registeredAdvCount = a1.Count;
                        if (registeredAdvCount >= clsSetting?.CountAdvInMounth)
                        {
                            //تاریخ روز اول ماه شمسی بعد را تنظیم می کند چون تا سر ماه بعد دیگر نیازی به این سیم کارت نیست
                            firstSimCardBusiness.NextUse = startDayOfNextMonthOfDateShToMiladi;
                            await firstSimCardBusiness.SaveAsync();

                            lstMessage.Clear();
                            lstMessage.Add(
                                $"سیمکارت {simCard.Number} به دلیل پر بودن آگهی ها در ماه موفق به ارسال آگهی نشد");
                            Utility.ShowBalloon("عدم ارسال آگهی", lstMessage);
                            await SendChat(clsSetting, simCard);

                            continue;
                        }

                        //آمار آگهی های ثبت شده امروز
                        var currentDate = DateTime.Now.Date;
                        var a2          = await AdvertiseLogBussines.GetAllAsync();

                        a2 = a2.Where(p =>
                                      p.SimCardNumber == card1 &&
                                      (p.StatusCode == StatusCode.Published ||
                                       p.StatusCode == StatusCode.InPublishQueue ||
                                       p.StatusCode == StatusCode.WaitForPayment) &&
                                      p.DateM >= currentDate).ToList();
                        registeredAdvCount = a2.Count;
                        if (registeredAdvCount >= clsSetting?.CountAdvInDay)
                        {
                            //تاریخ فردا رو ست می کند چون تا فردا دیگه نیازی به این سیم کارت نیست
                            firstSimCardBusiness.NextUse = DateTime.Today.AddDays(1);
                            await firstSimCardBusiness.SaveAsync();

                            lstMessage.Clear();
                            lstMessage.Add(
                                $"سیمکارت {simCard.Number} به دلیل پرپودن آگهی ها در روز موفق به ارسال آگهی نشد");
                            Utility.ShowBalloon("عدم ارسال آگهی", lstMessage);
                            await SendChat(clsSetting, simCard);

                            continue;
                        }

                        var shey = await SheypoorAdv.GetInstance();

                        await shey.StartRegisterAdv(simCard);

                        simCard.NextUse = DateTime.Now.AddMinutes(30);
                        await simCard.SaveAsync();
                        await Wait(2);
                    }

                    if (simCard.IsSendChat)
                    {
                        await SendChat(clsSetting, simCard);
                    }


                    CloseAllChromeWindows();



                    simCard.NextUse = DateTime.Now.AddHours(1);
                    await simCard.SaveAsync();
                }
                await Utility.Wait(10);

                lstMessage.Clear();
                lstMessage.Add("لیست کاملا پیمایش شد");
                Utility.ShowBalloon("اتمام یک دور کامل از پیمایش سیمکارت ها", lstMessage);
                await UpdateAdvStatus(clsSetting?.DayCountForUpdateState ?? 10);

                CloseAllChromeWindows();
            }
            catch (Exception ex)
            {
                WebErrorLog.ErrorInstence.StartErrorLog(ex);
            }
        }
示例#46
0
        private async Task <bool> ConnectInternalAsync()
        {
            for (int i = 1; i <= MAX_CONNECTION_ATTEMPTS; i++)
            {
                // Check if we still should connect:
                if (state != ConnectionState.CONNECTING)
                {
                    Logger.Debug(LOGGER_TAG + "Connection attempt canceled.");
                    return(false);
                }

                // Check if the network is up:
                if (!NetworkHelper.Instance.ConnectionInformation.IsInternetAvailable)
                {
                    lastConnectionError = new ConnectionError(ConnectionErrorCode.NO_INTERNET);
                    SetState(ConnectionState.ERROR, lastConnectionError);
                    Logger.Warn(LOGGER_TAG + "Unable to connect to " + account.serverAddress + " - no internet!");
                    return(false);
                }

                Logger.Debug(LOGGER_TAG + "Starting a connection attempt.");
                try
                {
                    // Setup socket:
                    socket = new StreamSocket();
                    socket.Control.KeepAlive        = true;
                    socket.Control.QualityOfService = SocketQualityOfService.LowLatency;
                    hostName = new HostName(account.serverAddress);

                    // Add all ignored certificate errors:
                    foreach (ChainValidationResult item in account.connectionConfiguration.IGNORED_CERTIFICATE_ERRORS)
                    {
                        socket.Control.IgnorableServerCertificateErrors.Add(item);
                    }

                    // Connect with timeout:
                    connectTimeoutCTS = disableConnectionTimeout ? new CancellationTokenSource() : new CancellationTokenSource(CONNECTION_TIMEOUT_MS);

                    // Start the connection process:
                    await socket.ConnectAsync(hostName, account.port.ToString(), SocketProtectionLevel.PlainSocket).AsTask(connectTimeoutCTS.Token);

                    // Setup stream reader and writer:
                    dataWriter = new DataWriter(socket.OutputStream);
                    dataReader = new DataReader(socket.InputStream)
                    {
                        InputStreamOptions = InputStreamOptions.Partial
                    };

                    // Update account connection info:
                    ConnectionInformation connectionInfo = account.CONNECTION_INFO;
                    connectionInfo.socketInfo = socket?.Information;

                    // Connection successfully established:
                    SetState(ConnectionState.CONNECTED);
                    return(true);
                }
                catch (TaskCanceledException e)
                {
                    Logger.Error(LOGGER_TAG + i + " try to connect to " + account.serverAddress + " failed:", e);
                    lastConnectionError = new ConnectionError(ConnectionErrorCode.CONNECT_TIMEOUT, e.Message);
                }
                catch (Exception e)
                {
                    OnConnectionError(e, i);
                }

                if (state == ConnectionState.CONNECTING)
                {
                    // Wait between connection attempts:
                    Logger.Info(LOGGER_TAG + "Starting delay between connection attempts...");
                    await Task.Delay(CONNECTION_ATTEMPT_DELAY);
                }
            }
            return(false);
        }
 public ExtendedXunitTestClassRunner(ITestClass testClass, IReflectionTypeInfo @class, IEnumerable<IXunitTestCase> testCases, IMessageSink diagnosticMessageSink, IMessageBus messageBus, ITestCaseOrderer testCaseOrderer, ExceptionAggregator aggregator, CancellationTokenSource cancellationTokenSource, IDictionary<Type, object> collectionFixtureMappings)
     : base(testClass, @class, testCases, diagnosticMessageSink, CreateHookableMessageBus(messageBus), testCaseOrderer, aggregator, cancellationTokenSource, collectionFixtureMappings)
 {
     _hookableSink = (HookableSink)this.MessageBus;
     _hookableSink.OnMessageHandler = OnMessage;
 }
示例#48
0
        // TODO: Tests

        private static void GetCoreSpeeds()
        {
            Process.GetCurrentProcess().PriorityClass = ProcessPriorityClass.High;

            for (var i = 0; i < information.Cpu.LogicalCores; i++)
            {
                if (i > 64)
                {
                    // Too long for long
                    break;
                }

                var core = information.Cpu.Cores.First(c => c.Number == i);

                core.NormalClockSpeed = information.Cpu.NormalClockSpeed;

                using var ct = new CancellationTokenSource();
                PerformanceCounter counter = null;

                if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
                {
                    counter =
                        new PerformanceCounter("Processor Information", "% Processor Performance", "0," + i);

                    counter.NextValue();
                }

                var thread = Util.RunAffinity(1uL << i, () =>
                        {
                        var g = 0;

                        while (!ct.IsCancellationRequested)
                        {
                            g++;
                        }
                    });

                Thread.Sleep(1000);

                var value = core.NormalClockSpeed;

                if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
                {
                    value = (uint)(counter.NextValue() / 100.0f * value);
                    counter.Dispose();
                }
                else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
                {
                    try
                    {
                        // KHz
                        var freq = ulong.Parse(
                            File.ReadAllText($"/sys/devices/system/cpu/cpu{i}/cpufreq/scaling_cur_freq"));

                        value = (uint)(freq / 1000);
                    }
                    catch (Exception)
                    {
                        // Abort early since failing once means we'll most likely fail always.
                        ct.Cancel();
                        break;
                    }
                }

                core.MaxClockSpeed = value;
                ct.Cancel();
                thread.Wait();
            }

            Process.GetCurrentProcess().PriorityClass = ProcessPriorityClass.Normal;
            information.Cpu.MaxClockSpeed =
                information.Cpu.Cores.Count > 0 ? information.Cpu.Cores.Max(c => c.MaxClockSpeed) : 0;
        }
 public ExtendedXunitTestCollectionRunner(ITestCollection testCollection, IEnumerable<IXunitTestCase> testCases, IMessageSink diagnosticMessageSink, IMessageBus messageBus, ITestCaseOrderer testCaseOrderer, ExceptionAggregator aggregator, CancellationTokenSource cancellationTokenSource)
     : base(testCollection, testCases, diagnosticMessageSink, messageBus, testCaseOrderer, aggregator, cancellationTokenSource)
 {
     this.diagnosticMessageSink = diagnosticMessageSink;
 }
示例#50
0
        public async Task SubscribePreloadProgress()
        {
            var cts = new CancellationTokenSource();

            var apvPrivateKey = new PrivateKey();
            var apv           = AppProtocolVersion.Sign(apvPrivateKey, 0);
            var genesisBlock  = BlockChain <EmptyAction> .MakeGenesisBlock();

            // 에러로 인하여 NineChroniclesNodeService 를 사용할 수 없습니다. https://git.io/JfS0M
            // 따라서 LibplanetNodeService로 비슷한 환경을 맞춥니다.
            // 1. 노드를 생성합니다.
            var seedNode = CreateLibplanetNodeService <EmptyAction>(genesisBlock, apv, apvPrivateKey.PublicKey);

            await StartAsync(seedNode.Swarm, cts.Token);

            // 2. Progress를 넘겨 preloadProgress subscription 과 연결합니다.
            var service = CreateLibplanetNodeService <EmptyAction>(
                genesisBlock,
                apv,
                apvPrivateKey.PublicKey,
                new Progress <PreloadState>(state =>
            {
                StandaloneContextFx.PreloadStateSubject.OnNext(state);
            }),
                new [] { seedNode.Swarm.AsPeer });

            var miner = new PrivateKey().ToAddress();
            await seedNode.BlockChain.MineBlock(miner);

            var result = await ExecuteQueryAsync("subscription { preloadProgress { currentPhase totalPhase extra { type currentCount totalCount } } }");

            Assert.IsType <SubscriptionExecutionResult>(result);

            service.StartAsync(cts.Token);

            await service.PreloadEnded.WaitAsync(cts.Token);

            var subscribeResult = (SubscriptionExecutionResult)result;
            var stream          = subscribeResult.Streams.Values.FirstOrDefault();

            // BlockHashDownloadState  : 1
            // BlockDownloadState      : 1
            // BlockVerificationState  : 1
            // ActionExecutionState    : 1
            const int preloadStatesCount     = 4;
            var       preloadProgressRecords =
                new List <(long currentPhase, long totalPhase, string type, long currentCount, long totalCount)>();
            var expectedPreloadProgress = new List <(long currentPhase, long totalPhase, string type, long currentCount, long totalCount)>
            {
                (1, 5, "BlockHashDownloadState", 1, 1),
                (2, 5, "BlockDownloadState", 1, 1),
                (3, 5, "BlockVerificationState", 1, 1),
                (5, 5, "ActionExecutionState", 1, 1),
            };

            foreach (var index in Enumerable.Range(1, preloadStatesCount))
            {
                var rawEvents = await stream.Take(index);

                var preloadProgress      = (Dictionary <string, object>)((Dictionary <string, object>)rawEvents.Data)["preloadProgress"];
                var preloadProgressExtra = (Dictionary <string, object>)preloadProgress["extra"];

                preloadProgressRecords.Add((
                                               (long)preloadProgress["currentPhase"],
                                               (long)preloadProgress["totalPhase"],
                                               (string)preloadProgressExtra["type"],
                                               (long)preloadProgressExtra["currentCount"],
                                               (long)preloadProgressExtra["totalCount"]));
            }

            Assert.True(preloadProgressRecords.ToImmutableHashSet().SetEquals(expectedPreloadProgress));

            await seedNode.StopAsync(cts.Token);

            await service.StopAsync(cts.Token);
        }
示例#51
0
        public Task <TResponse> SendAsync <TResponse>(string httpMethod, string absoluteUrl, object request, CancellationToken token = default(CancellationToken))
        {
            var client = GetHttpClient();

            if (!httpMethod.HasRequestBody() && request != null)
            {
                var queryString = QueryStringSerializer.SerializeToString(request);
                if (!string.IsNullOrEmpty(queryString))
                {
                    absoluteUrl += "?" + queryString;
                }
            }

            if (ResultsFilter != null)
            {
                var response = ResultsFilter(typeof(TResponse), httpMethod, absoluteUrl, request);
                if (response is TResponse)
                {
                    var tcs = new TaskCompletionSource <TResponse>();
                    tcs.SetResult((TResponse)response);
                    return(tcs.Task);
                }
            }

            if (token == default(CancellationToken))
            {
                if (CancelTokenSource == null)
                {
                    CancelTokenSource = new CancellationTokenSource();
                }
                token = CancelTokenSource.Token;
            }

            var httpReq       = CreateRequest(httpMethod, absoluteUrl, request);
            var sendAsyncTask = client.SendAsync(httpReq, token);

            if (typeof(TResponse) == typeof(HttpResponseMessage))
            {
                return((Task <TResponse>)(object) sendAsyncTask);
            }

            return(sendAsyncTask
                   .ContinueWith(responseTask =>
            {
                var httpRes = responseTask.Result;

                if (httpRes.StatusCode == HttpStatusCode.Unauthorized)
                {
                    if (RefreshToken != null)
                    {
                        var refreshDto = new GetAccessToken {
                            RefreshToken = RefreshToken
                        };
                        var uri = this.RefreshTokenUri ?? this.BaseUri.CombineWith(refreshDto.ToPostUrl());
                        return this.PostAsync <GetAccessTokenResponse>(uri, refreshDto)
                        .ContinueWith(t =>
                        {
                            if (t.IsFaulted)
                            {
                                var refreshEx = t.Exception.UnwrapIfSingleException() as WebServiceException;
                                if (refreshEx != null)
                                {
                                    throw new RefreshTokenException(refreshEx);
                                }
                                throw t.Exception;
                            }

                            var accessToken = t.Result?.AccessToken;
                            if (string.IsNullOrEmpty(accessToken))
                            {
                                throw new RefreshTokenException("Could not retrieve new AccessToken from: " + uri);
                            }

                            var refreshRequest = CreateRequest(httpMethod, absoluteUrl, request);
                            if (this.GetTokenCookie() != null)
                            {
                                this.SetTokenCookie(accessToken);
                            }
                            else
                            {
                                refreshRequest.AddBearerToken(this.BearerToken = accessToken);
                            }

                            return client.SendAsync(refreshRequest, token).ContinueWith(refreshTask =>
                                                                                        ConvertToResponse <TResponse>(refreshTask.Result,
                                                                                                                      httpMethod, absoluteUrl, refreshRequest, token),
                                                                                        token).Unwrap();
                        }, token).Unwrap();
                    }
                }

                return ConvertToResponse <TResponse>(httpRes, httpMethod, absoluteUrl, request, token);
            }, token).Unwrap());
        }
示例#52
0
 /// <summary>
 /// Wait for the specified handle to be signaled.
 /// </summary>
 /// <param name="handle">Handle to wait on.</param>
 /// <param name="cancellationSource">Cancellation token source to cancel if the user hits the cancel button.</param>
 public void Wait(WaitHandle handle, CancellationTokenSource cancellationSource)
 {
     throw new NotImplementedException();
 }
示例#53
0
        private static void StartServer(Options options)
        {
            logger.Info("==========================");
            logger.Info("Starting server...");

            var cancellationSource = new CancellationTokenSource();
            var cancellation       = cancellationSource.Token;

            Console.CancelKeyPress += (sender, e) =>
            {
                e.Cancel = true;
                logger.Info("Gracefully stopping server...");
                cancellationSource.Cancel();
            };

            var             threadPool        = new Core.ThreadPool(10, cancellation);
            IClientAcceptor acceptor          = new TcpClientAcceptor(options.Port);
            var             connectionManager = new ConnectionManager(acceptor, cancellation);
            var             broadcastingChat  = new BroadcastingChat(connectionManager, options.WelcomeMessage);
            var             commandShell      = new CommandShell("cmd", command => $"/c {command}");

            Func <ClientConnection, string, Task> processCommand = async(client, command) =>
            {
                Message reply;
                if (command.StartsWith("/c "))
                {
                    var task = commandShell.TryStartExecuting(command.Substring(3), TimeSpan.FromSeconds(10));
                    if (task == null)
                    {
                        reply = new Message {
                            Sender = "<server-shell>", Text = "Another command is already running."
                        }
                    }
                    ;
                    else
                    {
                        await broadcastingChat.ReplyTo(client, new Message { Sender = "<server-shell>", Text = $"Running `{command}`..." });

                        try { reply = new Message {
                                  Sender = "<server-shell>", Text = $"Execution result: {Environment.NewLine}{await task}"
                              }; }
                        catch (OperationCanceledException) { reply = new Message {
                                                                 Sender = "<server-shell>", Text = $"Execution timed out."
                                                             }; }
                    }
                }
                else
                {
                    reply = new Message {
                        Sender = "<server>", Text = $"Invalid command '{command}'"
                    }
                };

                await broadcastingChat.ReplyTo(client, reply);
            };

            broadcastingChat.IncomingMessageStrategy = incoming =>
            {
                var message = incoming.Message.Text.TrimStart();
                if (message.StartsWith("/"))
                {
                    return(processCommand(incoming.Sender, message));
                }
                else
                {
                    return(broadcastingChat.BroadcastToAll(incoming.Message));
                }
            };

            var tcs = new TaskCompletionSource <bool>();

            threadPool.Post(async() =>
            {
                logger.Info($"Start accepting clients at port {options.Port}");
                try
                {
                    await acceptor.Listen(cancellation);
                    logger.Info("Finish accepting clients");
                    tcs.TrySetResult(true);
                }
                catch (OperationCanceledException)
                {
                    tcs.SetCanceled();
                }
                catch (Exception ex)
                {
                    logger.Error(ex, "Error accepting clients");
                    tcs.SetException(ex);
                }
            });

            try
            {
                tcs.Task.Wait();
            }
            catch (AggregateException ex)
            {
                try { ex.Handle(exc => exc is OperationCanceledException); }
                catch (Exception innerEx) { logger.Error(innerEx); }
            }
            logger.Info("Server stopped");
        }
    }
 public MultiChunkCancellableServer(TestServer server, int cancelOnCall)
     : base(server)
 {
     _cancelOnCall       = cancelOnCall;
     _cancellationSource = new CancellationTokenSource();
 }
示例#55
0
        static void Main()
        {
            Console.WriteLine("WebRTC Server Sample Program");
            Console.WriteLine("Press ctrl-c to exit.");

            // Plumbing code to facilitate a graceful exit.
            CancellationTokenSource exitCts = new CancellationTokenSource(); // Cancellation token to stop the SIP transport and RTP stream.
            ManualResetEvent        exitMre = new ManualResetEvent(false);

            AddConsoleLogger();

            if (!File.Exists(MP4_FILE_PATH))
            {
                throw new ApplicationException($"The media file at does not exist at {MP4_FILE_PATH}.");
            }

            // Initialise OpenSSL & libsrtp, saves a couple of seconds for the first client connection.
            Console.WriteLine("Initialising OpenSSL and libsrtp...");
            Dtls.InitialiseOpenSSL();
            Srtp.InitialiseLibSrtp();

            // Initialise the Media Foundation library that will pull the samples from the mp4 file.
            _mfSampleGrabber = new SIPSorceryMedia.MFSampleGrabber();
            _mfSampleGrabber.OnClockStartEvent             += OnClockStartEvent;
            _mfSampleGrabber.OnVideoResolutionChangedEvent += OnVideoResolutionChangedEvent;
            unsafe
            {
                _mfSampleGrabber.OnProcessSampleEvent += OnProcessSampleEvent;
            }
            Task.Run(() => _mfSampleGrabber.Run(MP4_FILE_PATH, true));

            // Hook up event handlers to send the media samples to the network.
            //InitMediaToWebRtcClients();

            // Start web socket.
            Console.WriteLine("Starting web socket server...");
            _webSocketServer = new WebSocketServer(IPAddress.Any, WEBSOCKET_PORT, true);
            _webSocketServer.SslConfiguration.ServerCertificate          = new System.Security.Cryptography.X509Certificates.X509Certificate2(WEBSOCKET_CERTIFICATE_PATH);
            _webSocketServer.SslConfiguration.CheckCertificateRevocation = false;
            //_webSocketServer.Log.Level = WebSocketSharp.LogLevel.Debug;
            _webSocketServer.AddWebSocketService <SDPExchange>("/", (sdpExchanger) =>
            {
                sdpExchanger.WebSocketOpened   += SendSDPOffer;
                sdpExchanger.SDPAnswerReceived += SDPAnswerReceived;
            });
            _webSocketServer.Start();

            Console.WriteLine($"Waiting for browser web socket connection to {_webSocketServer.Address}:{_webSocketServer.Port}...");

            // Ctrl-c will gracefully exit the call at any point.
            Console.CancelKeyPress += delegate(object sender, ConsoleCancelEventArgs e)
            {
                e.Cancel = true;
                exitMre.Set();
            };

            // Wait for a signal saying the call failed, was cancelled with ctrl-c or completed.
            exitMre.WaitOne();

            _mfSampleGrabber.StopAndExit();
            _webSocketServer.Stop();
        }
        private async Task SelectSample(SampleInfo selectedSample)
        {
            if (selectedSample == null)
            {
                return;
            }

            // The following code removes the API key when using the Create and save map sample.
            if (nameof(SampleManager.Current.SelectedSample) != nameof(selectedSample))
            {
                // Remove API key if opening Create and save map sample.
                if (selectedSample.FormalName == "AuthorMap")
                {
                    ApiKeyManager.DisableKey();
                }
                // Restore API key if leaving Create and save map sample.
                else if (SampleManager.Current?.SelectedSample?.FormalName == "AuthorMap")
                {
                    ApiKeyManager.EnableKey();
                }
            }

            SampleTitleBlock.Text = selectedSample.SampleName;
            SampleManager.Current.SelectedSample = selectedSample;
            DescriptionContainer.SetSample(selectedSample);
            ShowSampleTab();

            // Call a function to clear any existing credentials from AuthenticationManager
            ClearCredentials();

            try
            {
                if (selectedSample.OfflineDataItems != null)
                {
                    CancellationTokenSource cancellationSource = new CancellationTokenSource();

                    // Show waiting page
                    SampleContainer.Content = new WPF.Viewer.WaitPage(cancellationSource);

                    // Wait for offline data to complete
                    await DataManager.EnsureSampleDataPresent(selectedSample, cancellationSource.Token);
                }

                // Show the sample
                SampleContainer.Content = SampleManager.Current.SampleToControl(selectedSample);
                SourceCodeContainer.LoadSourceCode();
            }
            catch (OperationCanceledException)
            {
                CategoriesRegion.Visibility = Visibility.Visible;
                SampleContainer.Visibility  = Visibility.Collapsed;
                return;
            }
            catch (Exception exception)
            {
                // failed to create new instance of the sample
                SampleContainer.Content = new WPF.Viewer.ErrorPage(exception);
            }

            CategoriesRegion.Visibility = Visibility.Collapsed;
            SampleContainer.Visibility  = Visibility.Visible;
        }
示例#57
0
 public Task ShowProgressMessageAsync(string message, string title, CancellationTokenSource cancellationToken)
 {
     throw new NotImplementedException();
 }
示例#58
0
 public void StartListening()
 {
     cts = new CancellationTokenSource();
     t   = server.Listening(address, port, cts.Token);
 }
示例#59
0
 public RetryTaskController()
 {
     _cts = new CancellationTokenSource();
 }
示例#60
0
        private void internalPerform()
        {
            using (abortToken = new CancellationTokenSource())
                using (timeoutToken = new CancellationTokenSource())
                    using (var linkedToken = CancellationTokenSource.CreateLinkedTokenSource(abortToken.Token, timeoutToken.Token))
                    {
                        try
                        {
                            PrePerform();

                            HttpRequestMessage request;

                            switch (Method)
                            {
                            default:
                                throw new InvalidOperationException($"HTTP method {Method} is currently not supported");

                            case HttpMethod.GET:
                                if (files.Count > 0)
                                {
                                    throw new InvalidOperationException($"Cannot use {nameof(AddFile)} in a GET request. Please set the {nameof(Method)} to POST.");
                                }

                                StringBuilder requestParameters = new StringBuilder();
                                foreach (var p in parameters)
                                {
                                    requestParameters.Append($@"{p.Key}={p.Value}&");
                                }
                                string requestString = requestParameters.ToString().TrimEnd('&');

                                request = new HttpRequestMessage(System.Net.Http.HttpMethod.Get, string.IsNullOrEmpty(requestString) ? Url : $"{Url}?{requestString}");
                                break;

                            case HttpMethod.POST:
                                request = new HttpRequestMessage(System.Net.Http.HttpMethod.Post, Url);

                                Stream postContent;

                                if (rawContent != null)
                                {
                                    if (parameters.Count > 0)
                                    {
                                        throw new InvalidOperationException($"Cannot use {nameof(AddRaw)} in conjunction with {nameof(AddParameter)}");
                                    }
                                    if (files.Count > 0)
                                    {
                                        throw new InvalidOperationException($"Cannot use {nameof(AddRaw)} in conjunction with {nameof(AddFile)}");
                                    }

                                    postContent         = new MemoryStream();
                                    rawContent.Position = 0;
                                    rawContent.CopyTo(postContent);
                                    postContent.Position = 0;
                                }
                                else
                                {
                                    if (!string.IsNullOrEmpty(ContentType) && ContentType != form_content_type)
                                    {
                                        throw new InvalidOperationException($"Cannot use custom {nameof(ContentType)} in a POST request.");
                                    }

                                    ContentType = form_content_type;

                                    var formData = new MultipartFormDataContent(form_boundary);

                                    foreach (var p in parameters)
                                    {
                                        formData.Add(new StringContent(p.Value), p.Key);
                                    }

                                    foreach (var p in files)
                                    {
                                        var byteContent = new ByteArrayContent(p.Value);
                                        byteContent.Headers.Add("Content-Type", "application/octet-stream");
                                        formData.Add(byteContent, p.Key, p.Key);
                                    }

                                    postContent = formData.ReadAsStreamAsync().Result;
                                }

                                requestStream = new LengthTrackingStream(postContent);
                                requestStream.BytesRead.ValueChanged += v =>
                                {
                                    reportForwardProgress();
                                    UploadProgress?.Invoke(v, contentLength);
                                };

                                request.Content = new StreamContent(requestStream);
                                if (!string.IsNullOrEmpty(ContentType))
                                {
                                    request.Content.Headers.ContentType = MediaTypeHeaderValue.Parse(ContentType);
                                }
                                break;
                            }

                            if (!string.IsNullOrEmpty(Accept))
                            {
                                request.Headers.Accept.TryParseAdd(Accept);
                            }

                            foreach (var kvp in headers)
                            {
                                request.Headers.Add(kvp.Key, kvp.Value);
                            }

                            reportForwardProgress();
                            using (request)
                                response = client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, linkedToken.Token).Result;

                            ResponseStream = CreateOutputStream();

                            switch (Method)
                            {
                            case HttpMethod.GET:
                                //GETs are easy
                                beginResponse(linkedToken.Token);
                                break;

                            case HttpMethod.POST:
                                reportForwardProgress();
                                UploadProgress?.Invoke(0, contentLength);

                                beginResponse(linkedToken.Token);
                                break;
                            }
                        }
                        catch (Exception) when(timeoutToken.IsCancellationRequested)
                        {
                            Complete(new WebException($"Request to {Url} timed out after {timeSinceLastAction / 1000} seconds idle (read {responseBytesRead} bytes).", WebExceptionStatus.Timeout));
                        }
                        catch (Exception) when(abortToken.IsCancellationRequested)
                        {
                            Complete(new WebException($"Request to {Url} aborted by user.", WebExceptionStatus.RequestCanceled));
                        }
                        catch (Exception e)
                        {
                            if (Completed)
                            {
                                // we may be coming from one of the exception blocks handled above (as Complete will rethrow all exceptions).
                                throw;
                            }

                            Complete(e);
                        }
                    }
        }