Windows 8 Store Apps Learning (48) multi-line threads other auxiliary classes

Source: Internet
Author: User
Tags datetime thread tostring volatile


Multi-line Threads other Auxiliary classes: SpinWait, Spinlock, Volatile, SynchronizationContext, Coredispatcher, ThreadLocal, ThreadStaticAttribute



Introduced



Re-imagine other auxiliary classes for multiple threading operations in Windows 8 Store Apps



SpinWait-Spin Wait



Spinlock-Spin Lock



Volatile-must be in memory



SynchronizationContext-Synchronizes data on a specified thread



Coredispatcher-Scheduler, for thread synchronization



ThreadLocal-for saving each thread's own data



ThreadStaticAttribute-The static variable specified is unique to each thread



Example



1. Demonstrate the use of spinwait



Thread/other/spinwaitdemo.xaml.cs


/ *
 * SpinWait-Spin wait, a low-level synchronization type. It will not give up any CPU time, but let the CPU wait in a loop
 *
 * Applicable scenarios: multi-core cpu, the expected waiting time is very short (a few microseconds)
 * This example is only used to describe the usage of SpinWait, and does not represent the applicable scenario
 * /
    
using System;
using System.Threading;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;
    
namespace XamlDemo.Thread.Other
{
    public sealed partial class SpinWaitDemo: Page
    {
        public SpinWaitDemo ()
        {
            this.InitializeComponent ();
        }
    
        protected override void OnNavigatedTo (NavigationEventArgs e)
        {
            lblMsg.Text = DateTime.Now.ToString ("mm: ss.fff");
    
            SpinWait.SpinUntil (
                () => // End the wait when the following conditions are met
                {
                    return false;
                }
                // If the specified condition has not been met after this timeout period has elapsed, the wait is forcibly ended
                , 1000);
    
            lblMsg.Text + = Environment.NewLine;
            lblMsg.Text + = DateTime.Now.ToString ("mm: ss.fff");
    
            SpinWait.SpinUntil (
                () => // End the wait when the following conditions are met
                {
                    return DateTime.Now.Second% 2 == 0;
                });
    
            lblMsg.Text + = Environment.NewLine;
            lblMsg.Text + = DateTime.Now.ToString ("mm: ss.fff");
        }
    }
}


2. Demonstrate the use of spinlock



Thread/other/spinlockdemo.xaml.cs


/ *
 * SpinLock-Spin lock, a low-level mutex. It will not give up any CPU time, but let the CPU wait indefinitely until the lock becomes available
 *
 * Applicable scenarios: multi-core cpu, the expected waiting time is very short (a few microseconds)
 * This example is only used to describe the usage of SpinLock, and does not represent the applicable scenario
 * /
    
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;
    
namespace XamlDemo.Thread.Other
{
    public sealed partial class SpinLockDemo: Page
    {
        private static int _count;
    
        public SpinLockDemo ()
        {
            this.InitializeComponent ();
        }
    
        protected async override void OnNavigatedTo (NavigationEventArgs e)
        {
            SpinLock spinLock = new SpinLock ();
    
            List <Task> tasks = new List <Task> ();
    
            // A total of 100 tasks are executed in parallel, and each task accumulates the same static variable 100000 times to simulate the scenario of concurrently accessing static variables
            for (int i = 0; i <100; i ++)
            {
                Task task = Task.Run (
                    () =>
                    {
                        bool lockTaken = false;
    
                        try
                        {
                            // IsHeld-whether the lock is currently occupied by any thread
                            // IsHeldByCurrentThread-whether the lock is occupied by the current thread
                            // To get the IsHeldByCurrentThread property, IsThreadOwnerTrackingEnabled must be true, which can be specified in the constructor, the default is true
    
                            // Enter the lock, lockTaken-whether the lock has been acquired
                            spinLock.Enter (ref lockTaken);
    
                            for (int j = 0; j <100000; j ++)
                            {
                                _count ++;
                            }
                        }
                        finally
                        {
                            // release the lock
                            if (lockTaken)
                                spinLock.Exit ();
                        }
                    });
    
                tasks.Add (task);
            }
    
            // wait for all tasks to complete
            await Task.WhenAll (tasks);
    
            lblMsg.Text = "count:" + _count.ToString ();
        }
    }
} 


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.