예제 #1
0
        public static void ForegroundThreadWithoutJoin()
        {
            ThreadLogger.Log("main start");
            var thread = new Thread(IntensiveOperationsService.OneSecondWork);

            thread.Start();
            ThreadLogger.Log("main end");
        }
예제 #2
0
        public static void TaskContinuations()
        {
            var task1 = Task.Run(() => IntensiveOperationsService.CancellableSleepingSum(1, 3));
            var task2 = task1.ContinueWith(t => ThreadLogger.Log($"The sum is {t.Result}"));
            var task3 = task2.ContinueWith(t => ThreadLogger.Log("Just a simple message from third task"));

            ThreadLogger.Log("Waiting for simple message from third task");
            //Needed to avoid mixing with other examples
            task3.Wait();
        }
예제 #3
0
        public async void OnNavigatedTo(NavigationContext navigationContext)
        {
            //Debug.WriteLine($"{nameof(View1ViewModel)} OnNavigatedTo");

            ThreadLogger.Log("Before loading View 1 data", GetType().Name);
            Text = "Loading View 1...";
            await DoSomethingAsync();

            Text = "View 1 Loaded Complete!";
            ThreadLogger.Log("After loading View 1 data", GetType().Name);
        }
예제 #4
0
        public static void CancellingTheTask()
        {
            var cts   = new CancellationTokenSource();
            var token = cts.Token;

            var task1 = Task.Run(() => IntensiveOperationsService.CancellableSleepingSum(1, 10, token), token);

            Thread.Sleep(2000);
            ThreadLogger.Log("Cancelling the cts");
            cts.Cancel();
        }
예제 #5
0
            public long FindEncryptionKey()
            {
                var firstLoopSize = FindLoopSize(PublicKeys[0]);

                ThreadLogger.LogLine($"firstLoopSize = {firstLoopSize}");

                var encryptionKey = Transform(PublicKeys[1], firstLoopSize);

                ThreadLogger.LogLine($"encryptionKey = {encryptionKey}");

                return(encryptionKey);
            }
        public static void QueueUserWorkItemAndCancelIt()
        {
            ThreadLogger.Log("main start");

            var cts   = new CancellationTokenSource();
            var token = cts.Token;

            System.Threading.ThreadPool.QueueUserWorkItem(x => IntensiveOperationsService.CancellableLoop(token));

            Thread.Sleep(3000);
            cts.Cancel();
            ThreadLogger.Log("main end");
        }
예제 #7
0
        public static void WaitAnyAndWaitAll()
        {
            var task1 = Task.Run(() => IntensiveOperationsService.CancellableSleepingSum(1, 1));
            var task2 = Task.Run(() => IntensiveOperationsService.CancellableSleepingSum(2, 2));
            var task3 = Task.Run(() => IntensiveOperationsService.CancellableSleepingSum(3, 3));

            var index = Task.WaitAny(task1, task2, task3);

            ThreadLogger.Log($"Task {index + 1} finished first");

            Task.WaitAll(task1, task2, task3);
            ThreadLogger.Log("All tasks finished");
        }
예제 #8
0
        static void Main(string[] args)
        {
            ThreadLogger logger = new ThreadLogger(new ConsoleLogWriter());

            logger.LogMethodNumber = 4;
            var test = new AATest(logger);

            test.UseInnerLogMethodNames = true;

            // WTF with this execution? See: https://habrahabr.ru/post/232169/ and https://msdn.microsoft.com/en-us/magazine/gg598924.aspx
            test.Execute();

            Console.WriteLine("Press any key to continue . . .");
            Console.ReadKey();
        }
        public static void CancellationTokenWithCallback()
        {
            ThreadLogger.Log("main start");

            var cts   = new CancellationTokenSource();
            var token = cts.Token;

            token.Register(() => ThreadLogger.Log("token has been cancelled"));

            System.Threading.ThreadPool.QueueUserWorkItem(x => IntensiveOperationsService.CancellableLoop(token));

            Thread.Sleep(3000);
            cts.Cancel();
            ThreadLogger.Log("main end");
        }
예제 #10
0
            public static long FindLoopSize(long publicKey)
            {
                long loopSize = 0;
                long v        = 1;

                do
                {
                    ++loopSize;
                    if (loopSize % 10000 == 0)
                    {
                        ThreadLogger.LogLine($"FindLoopSize({publicKey}) @{loopSize}");
                    }
                    v = (v * 7) % 20201227;
                }while (v != publicKey);
                return(loopSize);
            }
예제 #11
0
        public static void SimpleTaskCreation()
        {
            //Create and schedule a task via static method
            var task1 = Task.Run(() => IntensiveOperationsService.CancellableSleepingSum(1, 2));

            //Create a new task instance and schedule it via .Start() method
            var task2 = new Task <int>(n => IntensiveOperationsService.CancellableSleepingSum(2, (int)n), 2);

            task2.Start();

            //Create a task factory and use .StartNew() method to create and schedule a task
            TaskFactory tf    = new TaskFactory(/*Various options for all tasks created via this factory*/);
            var         task3 = tf.StartNew(() => IntensiveOperationsService.CancellableSleepingSum(3, 2));


            ThreadLogger.Log($"Task 1: {task1.Result}");
            ThreadLogger.Log($"Task 2: {task2.Result}");
            ThreadLogger.Log($"Task 3: {task3.Result}");
        }
예제 #12
0
        public static void TaskAndChildTasks()
        {
            var parent = new Task <int[]>(() =>
            {
                var results = new int[3];

                new Task(() => results[0] = IntensiveOperationsService.CancellableSleepingSum(1, 1), TaskCreationOptions.AttachedToParent).Start();
                new Task(() => results[1] = IntensiveOperationsService.CancellableSleepingSum(2, 2), TaskCreationOptions.AttachedToParent).Start();
                new Task(() => results[2] = IntensiveOperationsService.CancellableSleepingSum(3, 3), TaskCreationOptions.AttachedToParent).Start();

                return(results);
            });

            parent.ContinueWith(x => ThreadLogger.Log($"Sum of all results: {x.Result.Sum()}"));

            ThreadLogger.Log("Starting parrent task");
            parent.Start();
            //Needed to avoid mixing with other examples
            parent.Wait();
        }
예제 #13
0
        private static void StartWithContext()
        {
            Console.WriteLine($"2Has SynchronizationContext? {SynchronizationContext.Current != null}");
            using (new DummyForm()) {
                //SynchronizationContext.SetSynchronizationContext(new WindowsFormsSynchronizationContext());
                Console.WriteLine($"3Has SynchronizationContext? {SynchronizationContext.Current != null}");

                ThreadLogger logger = new ThreadLogger(new ConsoleLogWriter());
                logger.LogMethodNumber = 4;
                var test = new AATest(logger);
                test.UseInnerLogMethodNames = true;

                // WTF with this execution? See: https://habrahabr.ru/post/232169/ and https://msdn.microsoft.com/en-us/magazine/gg598924.aspx
                test.Execute();
                //new Thread(StartWithContext).Start(SynchronizationContext.Current);

                Console.WriteLine("Worker thread exited.");
            }
            Console.WriteLine($"4Has SynchronizationContext? {SynchronizationContext.Current != null}");
        }
예제 #14
0
        public static void TaskThrowsExceptionWhichIsNotObserved()
        {
            //Adding an event handler for unobserved exceptions
            TaskScheduler.UnobservedTaskException += (sender, e) =>
            {
                if (sender is Task task && task.Exception is AggregateException agg)
                {
                    var messages = agg.InnerExceptions.Select(ie => ie.Message).Aggregate((a, b) => a + ", " + b);
                    ThreadLogger.Log($"Within event handler - {messages}");
                }
            };

            //scheduling a task and not calling .Wait(), or accessing .Result or .Exception properties
            Task.Run(() => throw new Exception("Something's wrong!"));

            //ensure that the task will be garbage collected
            Thread.Sleep(1000);
            GC.WaitForPendingFinalizers();
            GC.Collect();
        }
        public static void LinkedCancellationTokens()
        {
            ThreadLogger.Log("main start");

            var cts1 = new CancellationTokenSource();

            cts1.Token.Register(() => ThreadLogger.Log("cts1 cancelled"));
            var cts2 = new CancellationTokenSource();

            cts2.Token.Register(() => ThreadLogger.Log("cts2 cancelled"));
            var cts = CancellationTokenSource.CreateLinkedTokenSource(cts1.Token, cts2.Token);

            cts.Token.Register(() => ThreadLogger.Log("linked cts cancelled"));

            System.Threading.ThreadPool.QueueUserWorkItem(x => IntensiveOperationsService.CancellableLoop(cts.Token));

            Thread.Sleep(3000);
            cts2.Cancel();
            ThreadLogger.Log("main end");
        }
        public static void CancellationTokenCallbackThrowingExceptionsWithAggregation()
        {
            ThreadLogger.Log("main start");

            var cts   = new CancellationTokenSource();
            var token = cts.Token;

            token.Register(() => throw new Exception("foo"));
            token.Register(() => throw new Exception("bar"));

            System.Threading.ThreadPool.QueueUserWorkItem(x => IntensiveOperationsService.CancellableLoop(token));

            Thread.Sleep(3000);
            try
            {
                cts.Cancel(false);
            }
            catch (AggregateException ex)
            {
                ThreadLogger.Log($"main exception: {ex.GetType()} - {ex.InnerExceptions.Select(e => e.Message).Aggregate((a, b) => a + ", " + b)}");
            }

            ThreadLogger.Log("main end");
        }
 private void TrataMensagemLog(LogMessage obj)
 {
     ThreadLogger.Instance().GeraLog(obj);
 }
예제 #18
0
 public AATest(ThreadLogger logWriter)
 {
     this.logWriter           = logWriter;
     logWriter.LogMethodDepth = 3;
 }
예제 #19
0
        private void AsyncAwaitTest_Load(object sender, EventArgs e)
        {
            logWriter = new ThreadLogger(new TextBoxLogWriter(textBoxDebug));

            var curContext = SynchronizationContext.Current;
        }
 public static void QueueUserWorkItem()
 {
     ThreadLogger.Log("main start");
     System.Threading.ThreadPool.QueueUserWorkItem(IntensiveOperationsService.OneSecondWork);
     ThreadLogger.Log("main end");
 }