Esempio n. 1
0
        /// <summary>
        ///     Initializes the <see cref="StaticRandom" /> class.
        /// </summary>
        static StaticRandom()
        {
            int seed = Environment.TickCount;

            ThreadLocal = new ThreadLocal<Random>(
                () => new Random(Interlocked.Increment(ref seed)));
        }
Esempio n. 2
0
        static void Main(string[] args)
        {
            Func<int> valueFactory = () => 1;
            ThreadLocal<int> tl = 
                new ThreadLocal<int>(valueFactory);

            LocalDataStoreSlot localDataStoreSlot = 
                Thread.GetNamedDataSlot("myThreadLocal");

            var value = valueFactory();

            Console.WriteLine("thread:{0} value:{1}", Thread.CurrentThread.ManagedThreadId, _value);
            _value = 10;
            ThreadStart action = () =>
            {
                _value = Thread.CurrentThread.ManagedThreadId;
                Console.WriteLine("thread:{0} value:{1}", Thread.CurrentThread.ManagedThreadId, _value);
            };

            var t1 = new Thread(action);
            var t2= new Thread(action);
            t1.Start();
            t2.Start();

            Console.ReadLine();


            var ints = new List<int>() {1, 2, 3, 4};
            var readOnlyCollection = ints.AsReadOnly();
            var count = readOnlyCollection.Count;

          
            
        }
Esempio n. 3
0
		public void InitializeThrowingTest ()
		{
			int callTime = 0;
			threadLocal = new ThreadLocal<int> (() => {
					Interlocked.Increment (ref callTime);
					throw new ApplicationException ("foo");
					return 43;
				});

			Exception exception = null;

			try {
				var foo = threadLocal.Value;
			} catch (Exception e) {
				exception = e;
			}

			Assert.IsNotNull (exception, "#1");
			Assert.IsInstanceOfType (typeof (ApplicationException), exception, "#2");
			Assert.AreEqual (1, callTime, "#3");

			exception = null;

			try {
				var foo = threadLocal.Value;
			} catch (Exception e) {
				exception = e;
			}

			Assert.IsNotNull (exception, "#4");
			Assert.IsInstanceOfType (typeof (ApplicationException), exception, "#5");
			Assert.AreEqual (1, callTime, "#6");
		}
Esempio n. 4
0
        public ChannelFactory(RawRabbitConfiguration config, IConnectionFactory connectionFactory)
        {
            _connectionFactory = connectionFactory;
            _accessDictionary = new ConcurrentDictionary<IModel, DateTime>();
            _config = config;
            _threadChannels = new ThreadLocal<IModel>(true);

            try
            {
                _logger.LogDebug("Connecting to primary host.");
                _connection = _connectionFactory.CreateConnection(_config.Hostnames);
                _logger.LogInformation("Successfully established connection.");
            }
            catch (BrokerUnreachableException e)
            {
                _logger.LogError("Unable to connect to broker", e);
                throw e.InnerException;
            }
            _closeTimer = new System.Threading.Timer(state =>
            {
                var enumerator = _accessDictionary.GetEnumerator();
                while (enumerator.MoveNext())
                {
                    if (DateTime.Now - enumerator.Current.Value > _config.RequestTimeout)
                    {
                        DateTime lastUsed;
                        if (_accessDictionary.TryRemove(enumerator.Current.Key, out lastUsed))
                        {
                            _logger.LogInformation($"Channel {enumerator.Current.Key.ChannelNumber} was last used {lastUsed}. Closing...");
                            enumerator.Current.Key.Close();
                        }
                    }
                }
            }, null, _config.RequestTimeout, _config.RequestTimeout);
        }
Esempio n. 5
0
 public void MultipleReferenceToValueTest()
 {
     if (Environment.Version.Major >= 4)
     {
         throw new NotSupportedException("Results in stack overflow - blame Microsoft");
     }
     Assert.Throws(
         typeof(InvalidOperationException),
         () =>
         {
             ThreadLocal<int>[] threadLocal = { null };
             using (threadLocal[0] = new ThreadLocal<int>(() => threadLocal[0] != null ? threadLocal[0].Value + 1 : 0, false))
             {
                 GC.KeepAlive(threadLocal[0].Value);
             }
         }
     );
     Assert.Throws(
         typeof(InvalidOperationException),
         () =>
         {
             ThreadLocal<int>[] threadLocal = { null };
             using (threadLocal[0] = new ThreadLocal<int>(() => threadLocal[0] != null ? threadLocal[0].Value + 1 : 0, true))
             {
                 GC.KeepAlive(threadLocal[0].Value);
             }
         }
     );
 }
        public FairPartitionResolver(IReadOnlyList<string> collectionLinks)
        {
            Guard.NotNull("collectionLinks", collectionLinks);

            this.collectionLinks = collectionLinks;
            this.random = new ThreadLocal<Random>(CreateNewRandom);
        }
        public void TestWithPointers()
        {
            var path = Path.Combine(new[] { "..", "..", "TestData", "MaxMind-DB", "test-data", "maps-with-pointers.raw" });
            var stream = new ThreadLocal<Stream>(() => new MemoryStream(File.ReadAllBytes(path)));
            using (stream)
            {
                var decoder = new Decoder(stream, 0);

                var node = decoder.Decode(0).Node;
                Assert.That(node.Value<string>("long_key"), Is.EqualTo("long_value1"));

                node = decoder.Decode(22).Node;
                Assert.That(node.Value<string>("long_key"), Is.EqualTo("long_value2"));

                node = decoder.Decode(37).Node;
                Assert.That(node.Value<string>("long_key2"), Is.EqualTo("long_value1"));

                node = decoder.Decode(50).Node;
                Assert.That(node.Value<string>("long_key2"), Is.EqualTo("long_value2"));

                node = decoder.Decode(55).Node;
                Assert.That(node.Value<string>("long_key"), Is.EqualTo("long_value1"));

                node = decoder.Decode(57).Node;
                Assert.That(node.Value<string>("long_key2"), Is.EqualTo("long_value2"));
            }
        }
        public void Run() 
        {
            //if (!File.Exists("WordLookup.txt"))    // Contains about 150,000 words
            //    new WebClient().DownloadFile(
            //      "http://www.albahari.com/ispell/allwords.txt", "WordLookup.txt");

            var wordLookup = new HashSet<string>(
              File.ReadAllLines("WordLookup.txt"),
              StringComparer.InvariantCultureIgnoreCase);

            // Random is not thread-safe,所以無法簡單的使用AsParallel,
            // 解決方法,使用locks 的方式包住random.Next
            // 參考網址:http://csharpindepth.com/Articles/Chapter12/Random.aspx
            var random = new Random();
            string[] wordList = wordLookup.ToArray();

            // Fortunately, the new ThreadLocal<T> class in .NET 4 makes it very easy to write providers which need to have a single instance per thread
            // 使用ThreadLocal,建立分開的Random object 給每一個Thread

            //new Random(參數), 是為了確保如果兩個Random objects 被建立在很短的時間,會回傳不同的亂數序列
            var allocationRandom = new ThreadLocal<Random>(() => new Random(Guid.NewGuid().GetHashCode()));
            
            // 隨機取100W的值塞給wordsToTest
            string[] wordsToTest = Enumerable.Range(0, 1000000)
                .AsParallel()
              .Select(i => wordList[allocationRandom.Value.Next(0, wordList.Length)])
              .ToArray();            
                    
            var startTime = DateTime.Now.Ticks;

            var endTime = DateTime.Now.Ticks;
            Console.WriteLine("Time : " + (endTime - startTime).ToString());

        }
Esempio n. 9
0
        public void TestBlockingQueueStress()
        {
            var queue = new BlockingQueue<int>(1);

            var rnd = new ThreadLocal<Random>(() => new Random());
            var generatedTotal = 0;
            var consummedTotal = 0;

            var producers = TestMonitorSimple.RunSimultanously(5, () =>
            {
                for (var i = 0; i < 1e6; i++)
                {
                    var value = rnd.Value.Next(100);
                    Interlocked.Add(ref generatedTotal, value);
                    queue.AddIfNotCompleted(value);
                }
            }, false);

            var consumers = TestMonitorSimple.RunSimultanously(5, () =>
            {
                foreach (var value in queue.GetConsumingEnumerable())
                {
                    Interlocked.Add(ref consummedTotal, value);
                }
            }, false);

            producers.ForEach(t => t.Join());
            queue.CompleteAdding();

            consumers.ForEach(t => t.Join());

            Assert.IsTrue(consummedTotal == generatedTotal);
        }
        public IModel GetChannel()
        {
            if (_threadModel == null)
            {
                _threadModel = new ThreadLocal<IModel>(() => _broker.GetConnection().CreateModel());
                _channelTimer = new Timer(state =>
                {
                    _threadModel?.Dispose();
                    _threadModel = null;
                }, null, TimeSpan.FromMilliseconds(200), new TimeSpan(-1));
            }
            else
            {
                _channelTimer.Change(TimeSpan.FromMilliseconds(100), new TimeSpan(-1));
            }

            if (_threadModel.IsValueCreated && _threadModel.Value.IsOpen)
            {
                return _threadModel.Value;
            }
            _threadModel?.Value?.Dispose();
            try
            {
                _threadModel.Value = _broker.GetConnection().CreateModel();
            }
            catch (ObjectDisposedException)
            {
                return GetChannel();
            }
            return _threadModel.Value;
        }
        /// <summary>Initializes the IOCompletionPortTaskScheduler.</summary>
        /// <param name="maxConcurrencyLevel">The maximum number of threads in the scheduler to be executing concurrently.</param>
        /// <param name="numAvailableThreads">The number of threads to have available in the scheduler for executing tasks.</param>
        public IOCompletionPortTaskScheduler(int maxConcurrencyLevel, int numAvailableThreads)
        {
            // Validate arguments
            if (maxConcurrencyLevel < 1) throw new ArgumentNullException("maxConcurrencyLevel");
            if (numAvailableThreads < 1) throw new ArgumentNullException("numAvailableThreads");

            m_tasks = new ConcurrentQueue<Task>();
            m_iocp = new IOCompletionPort(maxConcurrencyLevel);
            m_schedulerThread = new ThreadLocal<bool>();
            m_remainingThreadsToShutdown = new CountdownEvent(numAvailableThreads);

            // Create and start the threads
            for (int i = 0; i < numAvailableThreads; i++)
            {
                new Thread(() =>
                {
                    try
                    {
                        // Note that this is a scheduler thread.  Used for inlining checks.
                        m_schedulerThread.Value = true;

                        // Continually wait on the I/O completion port until
                        // there's a work item, then process it.
                        while (m_iocp.WaitOne())
                        {
                            Task next;
                            if (m_tasks.TryDequeue(out next)) TryExecuteTask(next);
                        }
                    }
                    finally { m_remainingThreadsToShutdown.Signal(); }
                }) { IsBackground = true }.Start();
            }
        }
 public HttpClient Client()
 {
     GatewayConfiguration = new HttpGatewayConfiguration();
     _timeout = Convert.ToDouble(GatewayConfiguration.OrderServiceConfiguration.Timeout);
     _client = new ThreadLocal<HttpClient>(() => CreateClient(_timeout));
     return _client.Value;
 }
Esempio n. 13
0
 private TracePipeline(DebugContext debugContext)
 {
     _debugContext = debugContext;
     _traceFrame = new ThreadLocal<DebugFrame>();
     debugContext.DebugCallback = this;
     debugContext.DebugMode = DebugMode.FullyEnabled;
 }
Esempio n. 14
0
 private void EnsureInitialized()
 {
     if (_random == null)
     {
         _random = new ThreadLocal<System.Random>(() => new System.Random(Seed.Value));
     }
 }
Esempio n. 15
0
 static ThreadLocalRandom()
 {
     lock (Seeder)
     {
         Seed = new ThreadLocal<int>(() => Seeder.Next());
     }
 }
Esempio n. 16
0
 public static void RunThreadLocalTest3_IsValueCreated()
 {
     ThreadLocal<string> tlocal = new ThreadLocal<string>(() => "Test");
     Assert.False(tlocal.IsValueCreated);
     string temp = tlocal.Value;
     Assert.True(tlocal.IsValueCreated);
 }
Esempio n. 17
0
        public static void RunThreadLocalTest4_Value()
        {
            ThreadLocal<string> tlocal = null;

            // different threads call Value
            int numOfThreads = 10;
            Task[] threads = new Task[numOfThreads];
            object alock = new object();
            List<string> seenValuesFromAllThreads = new List<string>();
            int counter = 0;
            tlocal = new ThreadLocal<string>(() => (++counter).ToString());
            //CancellationToken ct = new CancellationToken();
            for (int i = 0; i < threads.Length; ++i)
            {
                // We are creating the task using TaskCreationOptions.LongRunning because...
                // there is no guarantee that the Task will be created on another thread.
                // There is also no guarantee that using this TaskCreationOption will force
                // it to be run on another thread.
                threads[i] = new Task(() =>
                {
                    string value = tlocal.Value;
                    Debug.WriteLine("Val: " + value);
                    seenValuesFromAllThreads.Add(value);
                }, TaskCreationOptions.LongRunning);
                threads[i].Start(TaskScheduler.Default);
                threads[i].Wait();
            }
            Assert.Equal(Enumerable.Range(1, threads.Length).Select(x => x.ToString()), seenValuesFromAllThreads);
        }
 public ReplyAuthenticationSessionAttacher(
     AuthenticationSessionCache cache,
     AuthenticatedServerRegistry registry)
     : base(cache, registry)
 {
     address = new ThreadLocal<EndpointAddress>();
 }
Esempio n. 19
0
		static OAuthServerHelper()
		{
			RSAParameters privateRsaParameters;
			RSAParameters publicRsaParameters;
			using (var rsaKeyGen = new RSACryptoServiceProvider(RsaKeySize))
			{
				privateRsaParameters = rsaKeyGen.ExportParameters(true);
				publicRsaParameters = rsaKeyGen.ExportParameters(false);
			}

			Tuple<byte[], byte[]> aesKeyAndIV;
			using (var aesKeyGen = new AesCryptoServiceProvider())
			{
				aesKeyAndIV = Tuple.Create(aesKeyGen.Key, aesKeyGen.IV);
			}

			rsa = new ThreadLocal<RSACryptoServiceProvider>(() =>
			{
				var result = new RSACryptoServiceProvider();
				result.ImportParameters(privateRsaParameters);
				return result;
			});

			aes = new ThreadLocal<AesCryptoServiceProvider>(() =>
			{
				var result = new AesCryptoServiceProvider();
				result.Key = aesKeyAndIV.Item1;
				result.IV = aesKeyAndIV.Item2;
				return result;
			});

			rsaExponent = OAuthHelper.BytesToString(publicRsaParameters.Exponent);
			rsaModulus = OAuthHelper.BytesToString(publicRsaParameters.Modulus);
		}
Esempio n. 20
0
		public override void InitializeComponent()
		{
			base.InitializeComponent();
			CurrentFakeHleThreads = new ThreadLocal<HleThread>(() => new HleThread(PspEmulatorContext, new CpuThreadState(CpuProcessor)));
			//throw new NotImplementedException();
			//CurrentFakeHleThread = ;
		}
Esempio n. 21
0
 public SspSyllabifier(bool combineVowels, bool combineConsonants, bool vowelsSameSonorityTautosyllabic, SegmentPool segmentPool, IEnumerable<SonorityClass> sonorityScale)
     : base(combineVowels, combineConsonants)
 {
     _vowelsSameSonorityTautosyllabic = vowelsSameSonorityTautosyllabic;
     _segmentPool = segmentPool;
     _sonorityScale = sonorityScale.ToList();
     _initialOnsets = new ThreadLocal<HashSet<string>>();
 }
Esempio n. 22
0
        public void DefaultThreadLocalInitTest()
        {
            var local = new ThreadLocal<DateTime>();
            var local2 = new ThreadLocal<object>();

            Assert.AreEqual(default(DateTime), local.Value);
            Assert.AreEqual(default(object), local2.Value);
        }
Esempio n. 23
0
        public string Crack(List<string> plaintext, string target)
        {
            var targetBytes = HexHelper.StringToByteArray(target);
            ThreadLocal<MD5> md5 = new ThreadLocal<MD5>(() => MD5.Create());

            var match = plaintext.AsParallel().Where(p => ByteArrayCompare(targetBytes, md5.Value.ComputeHash(Encoding.Default.GetBytes(p)))).FirstOrDefault();
            return match;
        }
        /// <summary>
        /// Constructs a new JsonNetObjectSerializationProvider.
        /// </summary>
        /// <param name="engine">The engine to de/serialize dependent sub-objects.</param>
        public JsonNetObjectSerializationProvider(IStorageEngine engine = null)
        {
            _guidResolver = new ThreadLocal<SerializedItemsToGuidResolver>(() =>
                new SerializedItemsToGuidResolver(engine));

            _serializer = new ThreadLocal<JsonSerializer>(() =>
                JsonSerializer.Create(new JsonSerializerSettings() {ContractResolver = _guidResolver.Value }));
        }
Esempio n. 25
0
 public static void RunThreadLocalTest1_Ctor()
 {
     ThreadLocal<object> testObject;
     testObject = new ThreadLocal<object>();
     testObject = new ThreadLocal<object>(true);
     testObject = new ThreadLocal<object>(() => new object());
     testObject = new ThreadLocal<object>(() => new object(), true);
 }
        public ThreadLocalByteSegmentLocator(int memoryBlockSize)
        {
            _memoryBlockSize = memoryBlockSize;

            _currentBlock = new ThreadLocal<Tuple<byte[], int>>();

            RenewValue();
        }
Esempio n. 27
0
        protected override object OnInvoke(params object[] lastMappingValues)
        {
            if(GA.IsWebRuntime) return Webx.GetTemp(Id, () => this._lazyCallback.Value(lastMappingValues));

            if(this._local == null) this._local = new ThreadLocal<object>();
            if(!this._local.IsValueCreated) this._local.Value = this._lazyCallback.Value(lastMappingValues);
            return this._local.Value;
        }
Esempio n. 28
0
 public BaseClockSource()
 {
     clockEntries = new List<ClockEntry>();
     clockEntriesUpdateHandlers = new List<UpdateHandlerDelegate>();
     toNotify = new List<Action>();
     nearestTickIn = long.MaxValue;
     sync = new object();
     updateAlreadyInProgress = new ThreadLocal<bool>();
 }
Esempio n. 29
0
        public MsmqJobQueue(string pathPattern)
        {
            if (pathPattern == null) throw new ArgumentNullException("pathPattern");

            _pathPattern = pathPattern;

            _formatter = new ThreadLocal<IMessageFormatter>(
                () => new BinaryMessageFormatter());
        }
Esempio n. 30
0
 public InjectionRuntime(IApiBridge bridge, IDebuggerServer debuggerServer, ITimeSource timeSource)
 {
     interpreter = new ThreadLocal <Interpreter>(() => new Interpreter(Metadata, CurrentFileName, debuggerServer.Create()));
     Api         = new InjectionApi(bridge, Metadata, Globals, timeSource);
     RegisterNatives();
 }
Esempio n. 31
0
        public static void TestTryUpdate()
        {
            var dictionary = new ConcurrentDictionary <string, int>();

            Assert.Throws <ArgumentNullException>(
                () => dictionary.TryUpdate(null, 0, 0));
            // "TestTryUpdate:  FAILED.  TryUpdate didn't throw ANE when null key is passed");

            for (int i = 0; i < 10; i++)
            {
                dictionary.TryAdd(i.ToString(), i);
            }

            for (int i = 0; i < 10; i++)
            {
                Assert.True(dictionary.TryUpdate(i.ToString(), i + 1, i), "TestTryUpdate:  FAILED.  TryUpdate failed!");
                Assert.Equal(i + 1, dictionary[i.ToString()]);
            }

            //test TryUpdate concurrently
            dictionary.Clear();
            for (int i = 0; i < 1000; i++)
            {
                dictionary.TryAdd(i.ToString(), i);
            }

            var mres = new ManualResetEventSlim();

            Task[] tasks = new Task[10];
            ThreadLocal <ThreadData> updatedKeys = new ThreadLocal <ThreadData>(true);

            for (int i = 0; i < tasks.Length; i++)
            {
                // We are creating the Task using TaskCreationOptions.LongRunning because...
                // there is no guarantee that the Task will be created on another thread.
                // There is also no guarantee that using this TaskCreationOption will force
                // it to be run on another thread.
                tasks[i] = Task.Factory.StartNew((obj) =>
                {
                    mres.Wait();
                    int index                     = (((int)obj) + 1) + 1000;
                    updatedKeys.Value             = new ThreadData();
                    updatedKeys.Value.ThreadIndex = index;

                    for (int j = 0; j < dictionary.Count; j++)
                    {
                        if (dictionary.TryUpdate(j.ToString(), index, j))
                        {
                            if (dictionary[j.ToString()] != index)
                            {
                                updatedKeys.Value.Succeeded = false;
                                return;
                            }
                            updatedKeys.Value.Keys.Add(j.ToString());
                        }
                    }
                }, i, CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default);
            }

            mres.Set();
            Task.WaitAll(tasks);

            int numberSucceeded  = 0;
            int totalKeysUpdated = 0;

            foreach (var threadData in updatedKeys.Values)
            {
                totalKeysUpdated += threadData.Keys.Count;
                if (threadData.Succeeded)
                {
                    numberSucceeded++;
                }
            }

            Assert.True(numberSucceeded == tasks.Length, "One or more threads failed!");
            Assert.True(totalKeysUpdated == dictionary.Count,
                        string.Format("TestTryUpdate:  FAILED.  The updated keys count doesn't match the dictionary count, expected {0}, actual {1}", dictionary.Count, totalKeysUpdated));
            foreach (var value in updatedKeys.Values)
            {
                for (int i = 0; i < value.Keys.Count; i++)
                {
                    Assert.True(dictionary[value.Keys[i]] == value.ThreadIndex,
                                string.Format("TestTryUpdate:  FAILED.  The updated value doesn't match the thread index, expected {0} actual {1}", value.ThreadIndex, dictionary[value.Keys[i]]));
                }
            }

            //test TryUpdate with non atomic values (intPtr > 8)
            var dict = new ConcurrentDictionary <int, Struct16>();

            dict.TryAdd(1, new Struct16(1, -1));
            Assert.True(dict.TryUpdate(1, new Struct16(2, -2), new Struct16(1, -1)), "TestTryUpdate:  FAILED.  TryUpdate failed for non atomic values ( > 8 bytes)");
        }
Esempio n. 32
0
        [Category("NotDotNet")]          // nunit results in stack overflow
        public void MultipleReferenceToValueTest()
        {
            threadLocal = new ThreadLocal <int> (() => threadLocal.Value + 1);

            var value = threadLocal.Value;
        }
Esempio n. 33
0
        public HttpSocketServer(IServiceProvider locator)
        {
            this.Locator = locator;
            var endpoints   = new List <IPEndPoint>();
            var networkType = AddressFamily.InterNetworkV6;

            foreach (string key in ConfigurationManager.AppSettings.Keys)
            {
                if (key.StartsWith("HttpAddress", StringComparison.InvariantCultureIgnoreCase))
                {
                    var       addr = new Uri(ConfigurationManager.AppSettings[key]);
                    IPAddress ip;
                    if (!IPAddress.TryParse(addr.Host, out ip))
                    {
                        var ips = Dns.GetHostAddresses(addr.Host);
                        foreach (var i in ips)
                        {
                            if (i.AddressFamily == networkType)
                            {
                                endpoints.Add(new IPEndPoint(i, addr.Port));
                            }
                        }
                        if (endpoints.Count == 0 && ips.Length > 0)
                        {
                            if (ips[0].AddressFamily == AddressFamily.InterNetwork)
                            {
                                networkType = AddressFamily.InterNetwork;
                                foreach (var i in ips)
                                {
                                    if (i.AddressFamily == networkType)
                                    {
                                        endpoints.Add(new IPEndPoint(i, addr.Port));
                                    }
                                }
                            }
                        }
                    }
                    else
                    {
                        endpoints.Add(new IPEndPoint(ip, addr.Port));
                    }
                }
            }
            if (endpoints.Count == 0)
            {
                Console.WriteLine("Http address not found in config. Starting IPv6 on all interfaces");
                endpoints.Add(new IPEndPoint(Socket.OSSupportsIPv6 ? IPAddress.IPv6Any : IPAddress.Any, 8999));
            }
            else if (endpoints.FindAll(it => it.AddressFamily == AddressFamily.InterNetwork).Count == endpoints.Count)
            {
                networkType = AddressFamily.InterNetwork;
            }
            else if (endpoints.FindAll(it => it.AddressFamily == AddressFamily.InterNetworkV6).Count != endpoints.Count)
            {
                throw new ConfigurationErrorsException(@"Unable to setup configuration for both IPv4 and IPv6. Use either only IPv4 or IPv6. 
Please check settings: " + string.Join(", ", endpoints));
            }
            Socket = new Socket(networkType, SocketType.Stream, ProtocolType.Tcp);
            //Socket.SetSocketOption(SocketOptionLevel.IPv6, (SocketOptionName)27, 0);
            foreach (var ep in endpoints)
            {
                Socket.Bind(ep);
                Console.WriteLine("Bound to: " + ep);
            }
            var maxLen = ConfigurationManager.AppSettings["Revenj.ContentLengthLimit"];

            if (!string.IsNullOrEmpty(maxLen))
            {
                MessageSizeLimit = int.Parse(maxLen);
            }
            var ka = ConfigurationManager.AppSettings["Revenj.KeepAliveLimit"];

            if (!string.IsNullOrEmpty(ka))
            {
                KeepAliveTimeout = int.Parse(ka);
            }
            Routes = new Routes(locator);
            var customAuth = ConfigurationManager.AppSettings["CustomAuth"];

            if (!string.IsNullOrEmpty(customAuth))
            {
                var authType = Type.GetType(customAuth);
                if (!typeof(HttpAuth).IsAssignableFrom(authType))
                {
                    throw new ConfigurationErrorsException("Custom auth does not inherit from HttpAuth. Please inherit from " + typeof(HttpAuth).FullName);
                }
                Authentication = locator.Resolve <HttpAuth>(authType);
            }
            else
            {
                Authentication = locator.Resolve <HttpAuth>();
            }
            Context = new ThreadLocal <HttpSocketContext>(() => new HttpSocketContext("http://127.0.0.1/", MessageSizeLimit));
            var ca = ConfigurationManager.AppSettings["Revenj.HttpCapacity"];

            if (!string.IsNullOrEmpty(ca))
            {
                Requests = new BlockingCollection <RequestInfo>(new ConcurrentQueue <RequestInfo>(), int.Parse(ca));
            }
            else
            {
                Requests = new BlockingCollection <RequestInfo>(new ConcurrentQueue <RequestInfo>());
            }
        }
Esempio n. 34
0
 /// <summary>Initializes a new instance of the <see cref="ConcurrentBag{T}"/> class.</summary>
 public ConcurrentBag()
 {
     _locals = new ThreadLocal <WorkStealingQueue>();
 }
Esempio n. 35
0
 public RuntimeLocal()
 {
     this._threadLocal = new ThreadLocal <TValue>();
 }
Esempio n. 36
0
 static PerThreadContext()
 {
     _threadedContext = new ThreadLocal <PerThreadContext>();
 }
Esempio n. 37
0
            /// <summary>
            /// Sends the batch request to the server and clears the cache and the batchId.
            /// </summary>
            /// <param name="context">The context that sends the request.</param>
            /// <param name="cache">The cache containing the parameters of cached methods.</param>
            /// <param name="batchId">The batchId to retrieve the cached parameters.</param>
            /// <returns>A Task.</returns>
            internal static async Task ExecuteBatch(IContext context, ParametersCache cache, ThreadLocal <Guid> batchId)
            {
                if (!BatchHelper.IsInBatchMode(batchId))
                {
                    throw new InvalidOperationException("The calling thread was trying to do batch operation but it didn't begin the batch operations before.");
                }

                Guid localBatchId = batchId.Value;

                // Clears the batchId before executing the batch operation since after do "await" the original
                // thread will be used to do ExecuteBatchAsync and a new thread will be created to do the rest work.
                // So we will not be able to clear the original thread any more.
                batchId.Value = Guid.Empty;

                List <ParametersGroup> requests             = cache.GetParameters(localBatchId);
                List <TaskCompletionSource <object> > tasks = cache.GetTasks(localBatchId);

                try
                {
                    await context.ExecuteBatchAsync(requests, tasks);
                }
                catch
                {
                    throw;
                }
                finally
                {
                    // Clear the cache for this thread.
                    cache.Clear(localBatchId);
                }
            }
Esempio n. 38
0
 /// <summary>
 /// Checks if the current thread is in batch mode.
 /// </summary>
 /// <param name="batchId">The batchId of current thread.</param>
 /// <returns>True if current thread is in batch mode, otherwise false.</returns>
 internal static bool IsInBatchMode(ThreadLocal <Guid> batchId)
 {
     return(batchId != null && batchId.Value != null && batchId.Value != Guid.Empty);
 }
Esempio n. 39
0
 internal SpeechJournalSource(DiagnosticTrace trace = null)
 {
     lastActionJournalEntryId = new ThreadLocal <long>(false);
     this.trace = trace;
 }
Esempio n. 40
0
        private static void LazyAndThreadLocal()
        {
            //<snippet8>
            // Initialize the integer to the managed thread id of the
            // first thread that accesses the Value property.
            Lazy <int> number = new Lazy <int>(() => Thread.CurrentThread.ManagedThreadId);

            Thread t1 = new Thread(() => Console.WriteLine("number on t1 = {0} ThreadID = {1}",
                                                           number.Value, Thread.CurrentThread.ManagedThreadId));

            t1.Start();

            Thread t2 = new Thread(() => Console.WriteLine("number on t2 = {0} ThreadID = {1}",
                                                           number.Value, Thread.CurrentThread.ManagedThreadId));

            t2.Start();

            Thread t3 = new Thread(() => Console.WriteLine("number on t3 = {0} ThreadID = {1}", number.Value,
                                                           Thread.CurrentThread.ManagedThreadId));

            t3.Start();

            // Ensure that thread IDs are not recycled if the
            // first thread completes before the last one starts.
            t1.Join();
            t2.Join();
            t3.Join();

            /* Sample Output:
             *  number on t1 = 11 ThreadID = 11
             *  number on t3 = 11 ThreadID = 13
             *  number on t2 = 11 ThreadID = 12
             *  Press any key to exit.
             */
            //</snippet8>

            //<snippet9>
            // Initialize the integer to the managed thread id on a per-thread basis.
            ThreadLocal <int> threadLocalNumber = new ThreadLocal <int>(() => Thread.CurrentThread.ManagedThreadId);
            Thread            t4 = new Thread(() => Console.WriteLine("threadLocalNumber on t4 = {0} ThreadID = {1}",
                                                                      threadLocalNumber.Value, Thread.CurrentThread.ManagedThreadId));

            t4.Start();

            Thread t5 = new Thread(() => Console.WriteLine("threadLocalNumber on t5 = {0} ThreadID = {1}",
                                                           threadLocalNumber.Value, Thread.CurrentThread.ManagedThreadId));

            t5.Start();

            Thread t6 = new Thread(() => Console.WriteLine("threadLocalNumber on t6 = {0} ThreadID = {1}",
                                                           threadLocalNumber.Value, Thread.CurrentThread.ManagedThreadId));

            t6.Start();

            // Ensure that thread IDs are not recycled if the
            // first thread completes before the last one starts.
            t4.Join();
            t5.Join();
            t6.Join();

            /* Sample Output:
             * threadLocalNumber on t4 = 14 ThreadID = 14
             * threadLocalNumber on t5 = 15 ThreadID = 15
             * threadLocalNumber on t6 = 16 ThreadID = 16
             */
            //</snippet9>
        }
Esempio n. 41
0
 public Clock(Int32 maximumIdleTime)
 {
     m_MaximumIdleTime = TimeSpan.FromSeconds(maximumIdleTime).Ticks;
     m_StartTime       = new ThreadLocal <DateTime>(() => DateTime.UtcNow, false);
     m_StartTimestamp  = new ThreadLocal <Double>(() => Stopwatch.GetTimestamp(), false);
 }
Esempio n. 42
0
 private void InvalidateLastBlock()
 {
     lastBlockStorage = new ThreadLocal <Block>();
 }
Esempio n. 43
0
 internal LocalDataStoreSlot(ThreadLocal <object?> data)
 {
     Data = data;
     GC.SuppressFinalize(this);
 }
Esempio n. 44
0
        [PlatformSpecific(~TestPlatforms.Browser)] // Operation is not supported on this platform.
        public static void ValuesGetterDoesNotThrowUnexpectedExceptionWhenDisposed()
        {
            var startTest = new ManualResetEvent(false);
            var gotUnexpectedException    = new ManualResetEvent(false);
            ThreadLocal <int> threadLocal = null;
            bool stop = false;

            Action waitForCreatorDisposer;
            Thread creatorDisposer = ThreadTestHelpers.CreateGuardedThread(out waitForCreatorDisposer, () =>
            {
                startTest.CheckedWait();
                do
                {
                    var tl = new ThreadLocal <int>(trackAllValues: true);
                    Volatile.Write(ref threadLocal, tl);
                    tl.Value = 1;
                    tl.Dispose();
                } while (!Volatile.Read(ref stop));
            });

            creatorDisposer.IsBackground = true;
            creatorDisposer.Start();

            int readerCount    = Math.Max(1, Environment.ProcessorCount - 1);
            var waitsForReader = new Action[readerCount];

            for (int i = 0; i < readerCount; ++i)
            {
                Thread reader = ThreadTestHelpers.CreateGuardedThread(out waitsForReader[i], () =>
                {
                    startTest.CheckedWait();
                    do
                    {
                        var tl = Volatile.Read(ref threadLocal);
                        if (tl == null)
                        {
                            continue;
                        }

                        try
                        {
                            IList <int> values = tl.Values;
                        }
                        catch (ObjectDisposedException)
                        {
                        }
                        catch
                        {
                            gotUnexpectedException.Set();
                            throw;
                        }
                    } while (!Volatile.Read(ref stop));
                });
                reader.IsBackground = true;
                reader.Start();
            }

            startTest.Set();
            bool failed = gotUnexpectedException.WaitOne(500);

            Volatile.Write(ref stop, true);
            foreach (Action waitForReader in waitsForReader)
            {
                waitForReader();
            }
            waitForCreatorDisposer();
            Assert.False(failed);
        }
Esempio n. 45
0
        /// <summary>Visualize the partitioning.</summary>
        private void btnVisualize_Click(object sender, EventArgs e)
        {
            int  numProcs = tbCores.Value;
            int  width = pbPartitionedImage.Width, height = pbPartitionedImage.Height;
            bool useParallelFor = rbParallelFor.Checked, useParallelForEach = rbParallelForEach.Checked;

            _workFactor = tbWorkFactor.Value;

            // If we're using Parallel.ForEach or PLINQ, ensure a partitioning scheme was selected and use it
            Tuple <string, Func <int[], Partitioner <int> > > selectedMethod = null;

            if (!useParallelFor)
            {
                if (lvPartitioningMethods.SelectedIndices.Count == 0)
                {
                    return;
                }
                else
                {
                    selectedMethod = (Tuple <string, Func <int[], Partitioner <int> > >)lvPartitioningMethods.SelectedItems[0].Tag;
                }
            }

            // Make sure a workload was selected and use it
            if (lvWorkloads.SelectedItems.Count == 0)
            {
                return;
            }
            var selectedWorkload = (Tuple <string, Func <int, int, int> >)lvWorkloads.SelectedItems[0].Tag;

            // Create a new Bitmap to store the rendered output
            var bmp = new Bitmap(width, height);

            // Disable the start button and kick off the background work
            btnVisualize.Enabled = false;
            Task.Factory.StartNew(() =>
            {
                int nextId   = -1; // assign each thread a unique id
                var threadId = new ThreadLocal <int>(() => Interlocked.Increment(ref nextId));

                using (FastBitmap fastBmp = new FastBitmap(bmp)) // get faster access to the Bitmap's contents
                {
                    var sw = Stopwatch.StartNew();               // time the operation
                    if (useParallelFor)
                    {
                        Parallel.For(0, height, new ParallelOptions {
                            MaxDegreeOfParallelism = numProcs
                        }, i =>
                        {
                            int id = threadId.Value;
                            DoWork(selectedWorkload.Item2(height, i));
                            for (int j = 0; j < width; j++)
                            {
                                fastBmp.SetColor(j, i, _colors[id % _colors.Length]);
                            }
                        });
                    }
                    else
                    {
                        // Create the partitioner to be used
                        var partitioner = selectedMethod.Item2(Enumerable.Range(0, height).ToArray());

                        if (useParallelForEach)
                        {
                            // Run the work with Parallel.ForEach
                            Parallel.ForEach(partitioner, new ParallelOptions {
                                MaxDegreeOfParallelism = numProcs
                            }, i =>
                            {
                                int id = threadId.Value;
                                DoWork(selectedWorkload.Item2(height, i));
                                for (int j = 0; j < width; j++)
                                {
                                    fastBmp.SetColor(j, i, _colors[id % _colors.Length]);
                                }
                            });
                        }
                        else // PLINQ
                        {
                            // Run the work with PLINQ.  If a special partitioning method was selected, use relevant query operators
                            // to get PLINQ to use that partitioning approach.
                            var source = partitioner.AsParallel().WithDegreeOfParallelism(numProcs);
                            if (selectedMethod.Item1 == PartitioningStripe)
                            {
                                source = source.TakeWhile(elem => true);
                            }
                            else if (selectedMethod.Item1 == PartitioningHash)
                            {
                                source = source.Join(Enumerable.Range(0, height).AsParallel(), i => i, i => i, (i, ignore) => i);
                            }
                            source.ForAll(i =>
                            {
                                int id = threadId.Value;
                                DoWork(selectedWorkload.Item2(height, i));
                                for (int j = 0; j < width; j++)
                                {
                                    fastBmp.SetColor(j, i, _colors[id % _colors.Length]);
                                }
                            });
                        }
                    }

                    // Return the total time from the task
                    return(sw.Elapsed);
                }

                // When the work completes, run the following on the UI thread
            }).ContinueWith(t =>
            {
                // Dispose of the old image (if there was one) and display the new one
                var old = pbPartitionedImage.Image;
                pbPartitionedImage.Image = bmp;
                if (old != null)
                {
                    old.Dispose();
                }

                // Re-enable controls on the form and display the elapsed time
                btnVisualize.Enabled = true;
                lblTime.Text         = "Time: " + t.Result.ToString();
            }, TaskScheduler.FromCurrentSynchronizationContext());
        }
 internal Entry(ThreadLocal<T> threadLocal, T value)
 {
     this.weak.SetTarget(threadLocal);
     this.Value = value;
 }
Esempio n. 47
0
        public static void RunThreadLocalTest2_ToString()
        {
            ThreadLocal <object> tlocal = new ThreadLocal <object>(() => (object)1);

            Assert.Equal(1.ToString(), tlocal.ToString());
        }
Esempio n. 48
0
 public IPIReadWriteLockInternal(int numReaders)
 {
     _readIndicator   = new CLRAtomicInt[numReaders + 1];
     _thisReaderIndex = new ThreadLocal <int>();
 }
Esempio n. 49
0
        public static async Task AsyncMethodNotifications()
        {
            //
            // Define thread-local and async-local values.  The async-local value uses its notification
            // to keep the thread-local value in sync with the async-local value.
            //
            ThreadLocal <int> tls = new ThreadLocal <int>();
            AsyncLocal <int>  als = new AsyncLocal <int>(args =>
            {
                tls.Value = args.CurrentValue;
            });

            Assert.Equal(tls.Value, als.Value);

            als.Value = 1;
            Assert.Equal(tls.Value, als.Value);

            als.Value = 2;
            Assert.Equal(tls.Value, als.Value);

            await Run(async() =>
            {
                Assert.Equal(tls.Value, als.Value);
                Assert.Equal(2, als.Value);

                als.Value = 3;
                Assert.Equal(tls.Value, als.Value);

                Task t = Run(async() =>
                {
                    Assert.Equal(tls.Value, als.Value);
                    Assert.Equal(3, als.Value);

                    als.Value = 4;

                    Assert.Equal(tls.Value, als.Value);
                    Assert.Equal(4, als.Value);

                    await Task.Run(() =>
                    {
                        Assert.Equal(tls.Value, als.Value);
                        Assert.Equal(4, als.Value);

                        als.Value = 5;

                        Assert.Equal(tls.Value, als.Value);
                        Assert.Equal(5, als.Value);
                    });

                    Assert.Equal(tls.Value, als.Value);
                    Assert.Equal(4, als.Value);

                    als.Value = 6;

                    Assert.Equal(tls.Value, als.Value);
                    Assert.Equal(6, als.Value);
                });

                Assert.Equal(tls.Value, als.Value);
                Assert.Equal(3, als.Value);

                await Task.Yield();

                Assert.Equal(tls.Value, als.Value);
                Assert.Equal(3, als.Value);

                await t;

                Assert.Equal(tls.Value, als.Value);
                Assert.Equal(3, als.Value);
            });

            Assert.Equal(tls.Value, als.Value);
            Assert.Equal(2, als.Value);
        }
Esempio n. 50
0
        public static void TestMaxItemsPerTask(int maxConcurrency, int maxItemsPerTask, bool completeBeforeTaskWait)
        {
            //Create a custom TaskScheduler with specified max concurrency (TrackingTaskScheduler is defined in Common\tools\CommonUtils\TPLTestSchedulers.cs)
            TrackingTaskScheduler scheduler = new TrackingTaskScheduler(maxConcurrency);
            //We need to use the custom scheduler to achieve the results. As a by-product, we test to ensure custom schedulers are supported
            ConcurrentExclusiveSchedulerPair schedPair = new ConcurrentExclusiveSchedulerPair(scheduler, maxConcurrency, maxItemsPerTask);
            TaskFactory readers = new TaskFactory(schedPair.ConcurrentScheduler); //get reader and writer schedulers
            TaskFactory writers = new TaskFactory(schedPair.ExclusiveScheduler);

            //These are threadlocals to ensure that no concurrency side effects occur
            ThreadLocal <int> itemsExecutedCount    = new ThreadLocal <int>(); //Track the items executed by CEScheduler Task
            ThreadLocal <int> schedulerIDInsideTask = new ThreadLocal <int>(); //Used to store the Scheduler ID observed by a Task Executed by CEScheduler Task

            //Work done by both reader and writer tasks
            Action work = () =>
            {
                //Get the id of the parent Task (which is the task created by the scheduler). Each task run by the scheduler task should
                //see the same SchedulerID value since they are run on the same thread
                int id = ((TrackingTaskScheduler)scheduler).SchedulerID.Value;
                if (id == schedulerIDInsideTask.Value)
                { //since ids match, this is one more Task being executed by the CEScheduler Task
                    itemsExecutedCount.Value = ++itemsExecutedCount.Value;
                    //This does not need to be thread safe since we are looking to ensure that only n number of tasks were executed and not the order
                    //in which they were executed. Also asserting inside the thread is fine since we just want the test to be marked as failure
                    Assert.True(itemsExecutedCount.Value <= maxItemsPerTask, string.Format("itemsExecutedCount={0} cant be greater than maxValue={1}. Parent TaskID={2}",
                                                                                           itemsExecutedCount, maxItemsPerTask, id));
                }
                else
                {                                     //Since ids don't match, this is the first Task being executed in the CEScheduler Task
                    schedulerIDInsideTask.Value = id; //cache the scheduler ID seen by the thread, so other tasks running in same thread can see this
                    itemsExecutedCount.Value    = 1;
                }
                //Give enough time for a Task to stay around, so that other tasks will be executed by the same CEScheduler Task
                //or else the CESchedulerTask will die and each Task might get executed by a different CEScheduler Task. This does not affect the
                //verifications, but its increases the chance of finding a bug if the maxItemPerTask is not respected
                new ManualResetEvent(false).WaitOne(1);
            };

            List <Task> taskList           = new List <Task>();
            int         maxConcurrentTasks = maxConcurrency * maxItemsPerTask * 5;
            int         maxExclusiveTasks  = maxConcurrency * maxItemsPerTask * 2;

            // Schedule Tasks in both concurrent and exclusive mode
            for (int i = 0; i < maxConcurrentTasks; i++)
            {
                taskList.Add(readers.StartNew(work));
            }
            for (int i = 0; i < maxExclusiveTasks; i++)
            {
                taskList.Add(writers.StartNew(work));
            }

            if (completeBeforeTaskWait)
            {
                schedPair.Complete();
                schedPair.Completion.Wait();
                Assert.True(taskList.TrueForAll(t => t.IsCompleted), "All tasks should have completed for scheduler to complete");
            }

            //finally wait for all of the tasks, to ensure they all executed properly
            Task.WaitAll(taskList.ToArray());

            if (!completeBeforeTaskWait)
            {
                schedPair.Complete();
                schedPair.Completion.Wait();
                Assert.True(taskList.TrueForAll(t => t.IsCompleted), "All tasks should have completed for scheduler to complete");
            }
        }
Esempio n. 51
0
 /// <summary>释放所有会话</summary>
 internal void ReleaseSession()
 {
     //_store.Values.TryDispose();
     _store.TryDispose();
     _store = new ThreadLocal <IDbSession>();
 }
Esempio n. 52
0
 public void Setup()
 {
     nTimes      = 0;
     threadLocal = new ThreadLocal <int> (() => { Interlocked.Increment(ref nTimes); return(42); });
 }
 private void initialize()
 {
     locals = new ThreadLocal <Locals>(() => new Locals());
 }
Esempio n. 54
0
        public static void RunThreadLocalTest8_Values()
        {
            // Test adding values and updating values
            {
                var threadLocal = new ThreadLocal <int>(true);
                Assert.True(threadLocal.Values.Count == 0, "RunThreadLocalTest8_Values: Expected thread local to initially have 0 values");
                Assert.True(threadLocal.Value == 0, "RunThreadLocalTest8_Values: Expected initial value of 0");
                Assert.True(threadLocal.Values.Count == 1, "RunThreadLocalTest8_Values: Expected values count to now be 1 from initialized value");
                Assert.True(threadLocal.Values[0] == 0, "RunThreadLocalTest8_Values: Expected values to contain initialized value");

                threadLocal.Value = 1000;
                Assert.True(threadLocal.Values.Count == 1, "RunThreadLocalTest8_Values: Expected values count to still be 1 after updating existing value");
                Assert.True(threadLocal.Values[0] == 1000, "RunThreadLocalTest8_Values: Expected values to contain updated value");

                ((IAsyncResult)Task.Run(() => threadLocal.Value = 1001)).AsyncWaitHandle.WaitOne();
                Assert.True(threadLocal.Values.Count == 2, "RunThreadLocalTest8_Values: Expected values count to be 2 now that another thread stored a value");
                Assert.True(threadLocal.Values.Contains(1000) && threadLocal.Values.Contains(1001), "RunThreadLocalTest8_Values: Expected values to contain both thread's values");

                int    numTasks = 1000;
                Task[] allTasks = new Task[numTasks];
                for (int i = 0; i < numTasks; i++)
                {
                    // We are creating the task using TaskCreationOptions.LongRunning because...
                    // there is no guarantee that the Task will be created on another thread.
                    // There is also no guarantee that using this TaskCreationOption will force
                    // it to be run on another thread.
                    var task = Task.Factory.StartNew(() => threadLocal.Value = i, CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default);
                    task.Wait();
                }

                var values = threadLocal.Values;
                if (values.Count != 1002)
                {
                    string message =
                        "RunThreadLocalTest8_Values: Expected values to contain both previous values and 1000 new values. Actual count: " +
                        values.Count +
                        '.';
                    if (values.Count != 0)
                    {
                        message += " Missing items:";
                        for (int i = 0; i < 1002; i++)
                        {
                            if (!values.Contains(i))
                            {
                                message += " " + i;
                            }
                        }
                    }
                    Assert.True(false, message);
                }
                for (int i = 0; i < 1000; i++)
                {
                    Assert.True(values.Contains(i), "RunThreadLocalTest8_Values: Expected values to contain value for thread #: " + i);
                }

                threadLocal.Dispose();
            }

            // Test that thread values remain after threads depart
            {
                var tl = new ThreadLocal <string>(true);
                var t  = Task.Run(() => tl.Value = "Parallel");
                t.Wait();
                t = null;
                GC.Collect();
                GC.WaitForPendingFinalizers();
                GC.Collect();
                Assert.True(tl.Values.Count == 1, "RunThreadLocalTest8_Values: Expected values count to be 1 from other thread's initialization");
                Assert.True(tl.Values.Contains("Parallel"), "RunThreadLocalTest8_Values: Expected values to contain 'Parallel'");
            }
        }
Esempio n. 55
0
        protected override void InitializeCore()
        {
            base.InitializeCore();

            threadContext = new ThreadLocal <ThreadContext>(() => new ThreadContext(Context.GraphicsDevice), true);
        }
Esempio n. 56
0
 private static void InitializeDownloadFileWatcher()
 {
     _fileSystemWatcher = new ThreadLocal <FileSystemWatcher>(() => new FileSystemWatcher(GetSystemDownloadsPath()));
     _fileSystemWatcher.Value.Changed            += FilesChanged;
     _fileSystemWatcher.Value.EnableRaisingEvents = true;
 }
Esempio n. 57
0
        static void Main(string[] args)
        {
            var builder = new SqlConnectionStringBuilder()
            {
                DataSource = "test.db",
            };

            TypeMapper.SetSnakeToCamelCase <Model>();
            TypeMapper.SetSnakeToCamelCase <Texture>();
            TypeMapper.SetSnakeToCamelCase <ModelTextureId>();

#if false
            using (var conn = new SQLiteConnection(builder.ToString()))
            {
                conn.Open();
                conn.Execute("PRAGMA foreign_keys = ON");

                QueryBuilder.CreateTable <Model>(conn);
                QueryBuilder.CreateTable <Texture>(conn);

                conn.Execute("DROP TABLE IF EXISTS `model_texture_ids`");
                conn.Execute(string.Format(@"
CREATE TABLE `model_texture_ids` (
    `model_id` INTEGER,
    `texture_id` INTEGER,
    FOREIGN KEY(`model_id`) REFERENCES `models`(`id`) ON DELETE CASCADE ON UPDATE CASCADE,
    FOREIGN KEY(`texture_id`) REFERENCES `textures`(`id`) ON DELETE CASCADE ON UPDATE CASCADE,
    UNIQUE(`model_id`, `texture_id`)
)
"));
            }
#endif

            using (var conn = new SQLiteConnection(builder.ToString()))
            {
                conn.Open();
                conn.Execute("PRAGMA foreign_keys = ON");

                var iterations = 100000;
                var ids        = Enumerable.Range(0, iterations).OrderBy(_ => Guid.NewGuid()).ToArray();
                var rand       = new Random(0x12345678);

#if false
                var models = Enumerable.Range(0, iterations).Select(x => new Model()
                {
                    Name = $"model_{x}"
                }).ToArray();
                var textures = Enumerable.Range(0, iterations).Select(x => new Texture()
                {
                    Name = $"texture_{x}"
                }).ToArray();

                foreach (var model in models)
                {
                    var textureIds = Enumerable.Range(0, rand.Next(0, 5))
                                     .Select(_ => rand.Next(0, iterations))
                                     .Distinct();
                    model.Textures = textureIds.Select(x => textures[x]).ToArray();
                }

                using (new ScopedTimer())
                    using (var trans = conn.BeginTransaction())
                    {
                        foreach (var model in models)
                        {
                            conn.Execute("INSERT INTO `models` (`name`) values(@name)", new { name = model.Name });
                            model.Id = (int)conn.ExecuteScalar <long>("SELECT last_insert_rowid()");
                        }

                        foreach (var texture in textures)
                        {
                            conn.Execute("INSERT INTO `textures` (`name`) values(@name)", new { name = texture.Name });
                            texture.Id = (int)conn.ExecuteScalar <long>("SELECT last_insert_rowid()");
                        }

                        foreach (var model in models)
                        {
                            foreach (var texture in model.Textures)
                            {
                                conn.Execute(
                                    "INSERT INTO `model_texture_ids` (`model_id`, `texture_id`) values (@model_id, @texture_id)",
                                    new { model_id = model.Id, texture_id = texture.Id });
                            }
                        }

                        trans.Commit();
                    }

                using (new ScopedTimer())
                    using (var trans = conn.BeginTransaction())
                    {
                        for (var i = 0; i < iterations; ++i)
                        {
                            var model = models[ids[i]];
                            conn.Execute("UPDATE `models` SET `name`=@new_name WHERE `id`=@id", new { id = model.Id, new_name = $"{model.Name}_1" });
                        }
                        trans.Commit();
                    }
#endif

                GC.Collect();

                Model[] models;
                using (new ScopedTimer())
                {
                    var query = @"
SELECT * FROM `models` AS `m`
LEFT JOIN `model_texture_ids` AS `mt` ON `mt`.`model_id` = `m`.`id`
LEFT JOIN `textures` AS `t` ON `t`.`id` = `mt`.`texture_id`
";

                    var modelCache   = new Dictionary <int, Model>();
                    var textureCache = new Dictionary <int, Texture>();

                    models = conn.Query <Model, ModelTextureId, Texture, Model>(
                        query,
                        (m, _, t) =>
                    {
                        var isNew = false;

                        Model model;
                        if (!modelCache.TryGetValue(m.Id, out model))
                        {
                            model            = m;
                            model.Textures   = new List <Texture>();
                            modelCache[m.Id] = model;
                            isNew            = true;
                        }

                        if (t != null)
                        {
                            Texture tex;
                            if (!textureCache.TryGetValue(t.Id, out tex))
                            {
                                tex = t;
                                textureCache[t.Id] = tex;
                            }

                            model.Textures.Add(tex);
                        }

                        return(isNew ? model : null);
                    },
                        splitOn: "id,model_id,id")
                             .Where(x => x != null)
                             .ToArray();
                }
                Console.WriteLine(models.Length);
            }

#if false
            using (new ScopedTimer())
            {
                using (var conn = new ThreadLocal <SQLiteConnection>(() => { var item = new SQLiteConnection(builder.ToString()); item.Open(); return(item); }, true))
                {
                    Parallel.For(0, 100, i =>
                    {
                        Thread.Sleep(100);
                        using (var trans = conn.Value.BeginTransaction())
                        {
                            conn.Value.Execute("INSERT INTO `test_table` (`name`, `test_name`) values(@name, @test_name)", new { name = Guid.NewGuid().ToString(), test_name = "test_" + Guid.NewGuid().ToString() });
                        }
                    });

                    foreach (var item in conn.Values)
                    {
                        item.Dispose();
                    }
                }
            }

            using (new ScopedTimer())
            {
                using (var conn = new SQLiteConnection(builder.ToString()))
                {
                    conn.Open();
                    using (var trans = conn.BeginTransaction())
                    {
                        for (var i = 0; i < 100; ++i)
                        {
                            Thread.Sleep(100);
                            conn.Execute("INSERT INTO `test_table` (`name`, `test_name`) values(@name, @test_name)", new { name = Guid.NewGuid().ToString(), test_name = "test_" + Guid.NewGuid().ToString() });
                        }
                    }
                }
            }

            using (new ScopedTimer())
            {
                Parallel.For(0, 100, i => Thread.Sleep(100));
                using (var conn = new SQLiteConnection(builder.ToString()))
                {
                    conn.Open();
                    using (var trans = conn.BeginTransaction())
                    {
                        for (var i = 0; i < 100; ++i)
                        {
                            conn.Execute("INSERT INTO `test_table` (`name`, `test_name`) values(@name, @test_name)", new { name = Guid.NewGuid().ToString(), test_name = "test_" + Guid.NewGuid().ToString() });
                        }
                        trans.Commit();
                    }
                }
            }

            using (var conn = new SQLiteConnection(builder.ToString()))
            {
                SqlMapper.SetTypeMap(typeof(TestTable), new CustomPropertyTypeMap(typeof(TestTable), (type, name) =>
                {
                    // snake_case -> CamelCase
                    var propName = string.Join("", name.Split('_').Select(x => (x.Length > 1) ? x[0].ToString().ToUpper() + x.Substring(1) : x.ToUpper()));
                    return(type.GetProperty(propName));
                }));

                IEnumerable <TestTable> data;
                using (new ScopedTimer())
                {
                    data = conn.Query <TestTable>("SELECT * from `test_table`");
                }
                Console.WriteLine(data.Count());
            }
#endif

            Console.WriteLine("complete!!");
            Console.ReadKey();
        }
Esempio n. 58
0
 public BufferPoolThreadLocal(ISerializationService serializationService)
 {
     _threadLocal = new ThreadLocal <BufferPool>(() => new BufferPool(serializationService), false);
 }
 /// <summary>
 /// Cleans up the dispatcher helpers.
 /// </summary>
 public static void Reset()
 {
     s_isOnDispatcherThread.Dispose();
     s_isOnDispatcherThread = null;
     s_mainDispatcher       = null;
 }
Esempio n. 60
-1
        public void Run()
        {
            var wordLookupFile = Path.Combine(Path.GetTempPath(), "WordLookup.txt");

            if (!File.Exists(wordLookupFile))
            {
                new WebClient().DownloadFile("http://www.albahari.com/ispell/allwords.txt", wordLookupFile);
            }

            var wordLookup = new HashSet<string>(File.ReadAllLines(wordLookupFile), StringComparer.InvariantCultureIgnoreCase);
            var wordList = wordLookup.ToArray();

            // Here, we're using ThreadLocal to generate a thread-safe random number generator,
            // so we can parallelize the building of the wordsToTest array.
            var localRandom = new ThreadLocal<Random>(() => new Random(Guid.NewGuid().GetHashCode()));
            var wordsToTest = Enumerable.Range(0, 1000000)
                .AsParallel()
                .Select(i => wordList[localRandom.Value.Next(0, wordList.Length)])
                .ToArray();

            wordsToTest[12345] = "woozsh";     // Introduce a couple
            wordsToTest[23456] = "wubsie";     // of spelling mistakes.

            var query = wordsToTest
                .AsParallel()
                //.Select((word, index) => new IndexedWord { Word = word, Index = index })
                .Select((word, index) => new { Word = word, Index = index })
                .Where(iword => !wordLookup.Contains(iword.Word))
                .OrderBy(iword => iword.Index);

            var result = query.ToList();
        }