Example #1
0
        private void Document_Move_Before(object sender, DocumentEventArgs e)
        {
            // Add track of the Document's original Parent ID so we can rebuild on that after moved.
            var Slot = Thread.AllocateNamedDataSlot("PreviousParentIDForNode_" + e.Node.NodeID);

            Thread.SetData(Slot, e.Node.NodeParentID);
        }
Example #2
0
        /// <summary>
        /// Crée le DbContext et le stoque dans la TLS du Thread d'exécution.
        /// </summary>
        /// <param name="type">Type de DbContext.</param>
        /// <param name="key">Clef de stockage.</param>
        /// <param name="connectionString">Chaine de connexion.</param>
        /// <returns>Le DbContext.</returns>
        private static object GetThreadScopedDbContextInternal(Type type, string key, string connectionString)
        {
            if (key == null)
            {
                key = "__THSCDC_" + Thread.CurrentContext.ContextID.ToString(CultureInfo.InvariantCulture);
            }

            LocalDataStoreSlot threadData = Thread.GetNamedDataSlot(key);
            object             context    = null;

            if (threadData != null)
            {
                context = Thread.GetData(threadData);
            }

            if (context == null)
            {
                context = connectionString == null?Activator.CreateInstance(type) : Activator.CreateInstance(type, connectionString);

                if (context != null)
                {
                    if (threadData == null)
                    {
                        threadData = Thread.AllocateNamedDataSlot(key);
                    }

                    Thread.SetData(threadData, context);
                }
            }

            return(context);
        }
Example #3
0
        public ToUpperOp(string name) : base(name)
        {
            var ebc = new ToUpperEBC();

            ebc.Result += _ =>
            {
                var continueWith = (Action <IMessage>)Thread.GetData(
                    Thread.GetNamedDataSlot("continueWith")
                    );
                continueWith(new Message(base.Name, _));
            };

            _adapter = (input, continueWith, unhandledException) =>
            {
                Thread.AllocateNamedDataSlot("continueWith");
                Thread.SetData(Thread.GetNamedDataSlot("continueWith"),
                               continueWith);
                try
                {
                    ebc.Process((string)input.Data);
                }
                finally
                {
                    Thread.FreeNamedDataSlot("continueWith");
                }
            };
        }
Example #4
0
        public override DbManagerProxy Create(ModelUserContext context = null, CacheScope cacheScope = null)
        {
            DbManagerProxy     ret;
            LocalDataStoreSlot slot = Thread.GetNamedDataSlot(DbManagerProxy.NameDbManagerSlot(m_DatabaseType));

            if (slot != null)
            {
                ret = Thread.GetData(slot) as DbManagerProxy;
                if (ret != null)
                {
                    ret.IncrementRef();
                    return(ret);
                }
            }
            else
            {
                slot = Thread.AllocateNamedDataSlot(DbManagerProxy.NameDbManagerSlot(m_DatabaseType));
            }

            var connectionString = (context != null && context.IsArchiveMode)
                ? context.DatabaseConnectionString
                : m_ConnectionString;

            ret = new DbManagerProxy(new SqlDataProvider(), connectionString, context, cacheScope, m_DatabaseType);
            ret.IncrementRef();
            Thread.SetData(slot, ret);
            return(ret);
        }
Example #5
0
        static void Main(string[] args)
        {
            //Thread.AllocateDataSlot("token");
            //在所有现成上分配了token得槽位
            var slot = Thread.AllocateNamedDataSlot("token");

            //主线程上设置槽位,token只能被主线程读取,其他线程无法读取
            Thread.SetData(slot, Guid.NewGuid().ToString());
            //Thread.FreeNamedDataSlot("");
            var t = new Thread(() =>
            {
                // Thread.SetData(slot, Guid.NewGuid().ToString());
                var obj = Thread.GetData(slot);

                Console.WriteLine("当前工作线程:{0}", obj);
            });

            t.Start();

            var obj2 = Thread.GetData(slot);

            Console.WriteLine("主线程:{0}", obj2);

            Console.Read();
        }
        private static object GetThreadScopedDataContextInternal(Type type, string key, string ConnectionString)
        {
            if (key == null)
            {
                key = defaultKey;                          //+ Thread.CurrentContext.ContextID;
            }
            LocalDataStoreSlot threadData = Thread.GetNamedDataSlot(key);
            object             context    = null;

            if (threadData != null)
            {
                context = Thread.GetData(threadData);
            }

            if (context == null)
            {
                context = CreateInstance(ConnectionString, type);

                if (context != null)
                {
                    if (threadData == null)
                    {
                        threadData = Thread.AllocateNamedDataSlot(key);
                    }

                    Thread.SetData(threadData, context);
                }
            }

            return(context);
        }
Example #7
0
        public ThreadLocalStorageProvider()
        {
            Thread.AllocateNamedDataSlot(namedDataSlot);
            LocalDataStoreSlot threadData = Thread.GetNamedDataSlot(namedDataSlot);

            Thread.SetData(threadData, new Dictionary <string, object>());
        }
Example #8
0
        /// <summary>
        /// 有名字的数据插槽
        /// </summary>
        public void Fun2()
        {
            var solt = Thread.AllocateNamedDataSlot("name");

            Thread.SetData(solt, "cheng");

            Thread t2 = new Thread(() =>
            {
                var age = Thread.GetData(solt);
            });

            Thread t = new Thread(() => {
                //工作线程
                var name2 = Thread.GetData(solt);

                solt = Thread.AllocateNamedDataSlot("age");

                Thread.SetData(solt, 12);

                var age = Thread.GetData(solt);

                t2.Start();
            });

            t.Start();

            //主线程
            var name = Thread.GetData(solt);
        }
        public static void Thread_NamedDataSlot()
        {
            //There is an other way to create data slots for threads

            Thread.AllocateNamedDataSlot("Lovi88");

            Action a2 = () =>
            {
                for (int i = 0; i < 5; i++)
                {
                    //setting the data in local storage
                    Thread.SetData(Thread.GetNamedDataSlot("Lovi88"), Thread.CurrentThread.Name);

                    Thread.Sleep(5);

                    //retrieving data
                    var data = Thread.GetData(Thread.GetNamedDataSlot("Lovi88"));
                    Debug.WriteLine($"ThreadName: {Thread.CurrentThread.Name} data: {data}");
                }
            };

            var t3 = new Thread((() => a2()))
            {
                Name = "t3"
            };
            var t4 = new Thread((() => a2()))
            {
                Name = "t4"
            };

            t3.Start();
            t4.Start();

            Debug.WriteLine("ended");
        }
Example #10
0
    public static int Main()
    {
        Console.WriteLine("Hello, World!");
        slot = Thread.AllocateDataSlot();
        LocalDataStoreSlot namedslot = Thread.AllocateNamedDataSlot("data-slot");

        Test   test = new Test();
        Thread thr  = new Thread(new ThreadStart(test.Thread_func));

        thr.Start();
        Thread.Sleep(1000);
        Thread main = Thread.CurrentThread;

        main.Name = "wibble";
        Thread othermain = Thread.CurrentThread;

        Console.WriteLine("Other name " + othermain.Name);
        Thread.Sleep(0);

        Console.WriteLine("In the main line!");

        Console.WriteLine("Trying to enter lock");
        if (Monitor.TryEnter(thr, 100) == true)
        {
            Console.WriteLine("Returned lock");
            Monitor.Exit(thr);
        }
        else
        {
            Console.WriteLine("Didn't get lock");
        }

        Thread.SetData(slot, main);
        Thread storedthr = (Thread)Thread.GetData(slot);

        Console.WriteLine("Stored subthread is " + storedthr.Name);

        Thread.SetData(namedslot, main);
        storedthr = (Thread)Thread.GetData(namedslot);
        Console.WriteLine("Stored subthread is " + storedthr.Name);

        if (thr.Join(5000))
        {
            Console.WriteLine("Joined thread");
        }
        else
        {
            Console.WriteLine("Didn't join thread");
        }

        lock (thr) {
            Monitor.Pulse(thr);
            Console.WriteLine("Signalled thread");
        }

        thr.Join();

        return(0);
    }
Example #11
0
        public void OnSerializing(StreamingContext context)
        {
            var slot = Thread.AllocateNamedDataSlot("C");

            Thread.SetData(slot, PropertyA);

            PropertyA = Convert.ToBase64String(Encoding.UTF8.GetBytes(PropertyA));
        }
Example #12
0
        public void Initialize()
        {
#if NETCOREAPP2_1_OR_GREATER
            //TODO: check if this can be removed, was possibly just a hacking artefact
            Thread.AllocateNamedDataSlot("foo");
            Thread.FreeNamedDataSlot("foo");
#endif
        }
        /// <summary>
        /// Guarda un objeto o valor en un espacio de memoria disponible sólo para el hilo actual.
        /// </summary>
        /// <remarks>
        ///     Registro de versiones:
        ///
        ///         1.0 03/11/2015 Marcos Abraham Hernández Bravo (Ada Ltda.): versión inicial.
        /// </remarks>
        /// <param name="hilo">Hilo de origen.</param>
        /// <param name="nombre">Nombre del valor a guardar.</param>
        /// <param name="data">Valor a guardar.</param>
        public static void Guardar(this Thread hilo, string nombre, object data)
        {
            LocalDataStoreSlot slot = Thread.GetNamedDataSlot(nombre);

            if (slot == null)
            {
                slot = Thread.AllocateNamedDataSlot(nombre);
            }
            Thread.SetData(slot, data);
        }
Example #14
0
        public static void UseNamedSlots()
        {
            Thread.AllocateNamedDataSlot("SlotName");
            Thread.SetData(Thread.GetNamedDataSlot("SlotName"), new SomeData());

            object data = Thread.GetData(Thread.GetNamedDataSlot("SlotName"));

            Console.WriteLine(data);
            Thread.FreeNamedDataSlot("SlotName");
        }
Example #15
0
 public NmqiEnvironment(NmqiPropertyHandler nmqiPropertyHandler)
 {
     base.TrConstructor("%Z% %W%  %I% %E% %U%", new object[] { nmqiPropertyHandler });
     this.properties = nmqiPropertyHandler;
     bitmode         = Convert.ToString(Marshal.SizeOf(typeof(IntPtr)));
     this.cfg        = new MQClientCfg(this);
     this.cfg.FindAndParse();
     if (Thread.GetNamedDataSlot("MQ_CLIENT_THREAD_TYPE") == null)
     {
         Thread.AllocateNamedDataSlot("MQ_CLIENT_THREAD_TYPE");
     }
 }
Example #16
0
        public void Setup()
        {
            var slot1 = Thread.AllocateNamedDataSlot("SlotPrimitive");

            Thread.SetData(slot1, 0);
            var slot2 = Thread.AllocateNamedDataSlot("SlotManaged");

            Thread.SetData(slot2, new SomeData());
            threadValueLocal     = new ThreadLocal <int>(() => 0);
            threadReferenceLocal = new ThreadLocal <SomeData>(() => new SomeData());
            referenceLocal       = new SomeData();
        }
Example #17
0
        public static T Resolve <T>(string key, Func <T> factory)
        {
            if (Slots.ContainsKey(key) == false)
            {
                Slots[key] = Thread.AllocateNamedDataSlot(key);
                var factoryVal = factory();
                Thread.SetData(Slots[key], factoryVal);
            }
            var value = Thread.GetData(Slots[key]);

            return((T)value);
        }
Example #18
0
        public void invoke(object obj)
        {
            m_taskStatus = Task.Factory.StartNew(new Action(status));
            Tuple <object, int> arg = obj as Tuple <object, int>;
            object instance         = arg.Item1;
            int    nGpuId           = arg.Item2;

            try
            {
                LocalDataStoreSlot lds = Thread.GetNamedDataSlot("GPUID");
                if (lds == null)
                {
                    lds = Thread.AllocateNamedDataSlot("GPUID");
                }

                if (lds != null)
                {
                    Thread.SetData(lds, nGpuId.ToString());
                }

                m_swTiming.Reset();
                m_swTiming.Start();
                m_status = STATUS.Running;
                m_mi.Invoke(instance, null);
                m_status = STATUS.Passed;
            }
            catch (Exception excpt)
            {
                if (excpt.Message == "Aborted!" || (excpt.InnerException != null && excpt.InnerException.Message == "Aborted!"))
                {
                    m_status = STATUS.Aborted;
                }
                else
                {
                    m_status = STATUS.Failed;
                    m_errorInfo.SetError(excpt);
                }
            }
            finally
            {
                m_swTiming.Stop();

                if (m_miDispose != null)
                {
                    m_miDispose.Invoke(instance, null);
                }

                m_evtStatusCancel.Set();
                Thread.FreeNamedDataSlot("GPUID");
            }
        }
    public override void Before(MethodInfo methodUnderTest)
    {
        // Don't ever set the verbosity on release builds just in case
        // we forget the attribute in a commit ;)
#if DEBUG
        var data = Thread.GetNamedDataSlot(nameof(LoggerVerbosity));
        if (data == null)
        {
            data = Thread.AllocateNamedDataSlot(nameof(LoggerVerbosity));
        }

        Thread.SetData(data, Verbosity);
#endif

        base.Before(methodUnderTest);
    }
    public override void Before(MethodInfo methodUnderTest)
    {
        // Don't ever set this flag on release builds just in case
        // we forget the attribute in a commit ;)
#if DEBUG
        var data = Thread.GetNamedDataSlot(nameof(OpenBuildLogAttribute));
        if (data == null)
        {
            data = Thread.AllocateNamedDataSlot(nameof(OpenBuildLogAttribute));
        }

        Thread.SetData(data, new object());
#endif

        base.Before(methodUnderTest);
    }
Example #21
0
        public static void Main()
        {
            Thread.AllocateNamedDataSlot("ErrNo");
            Thread.AllocateNamedDataSlot("ErrSource");
            Thread th2 = new Thread(new ThreadStart(SetError));

            th2.Name = "t2";
            th2.Start();
            Thread th3 = new Thread(new ThreadStart(SetError));

            th3.Name = "t3";
            th3.Start();
            Thread.FreeNamedDataSlot("ErrNo");
            Thread.FreeNamedDataSlot("ErrSource");
            Console.Read();
        }
Example #22
0
 public ISession GetCurrentSession()
 {
     if (HttpContext.Current.Session != null)
     {
         return(HttpContext.Current.Session[SessionStorageName] as ISession);
     }
     else
     {
         var storage = Thread.GetNamedDataSlot(SessionStorageName);
         if (storage == null)
         {
             storage = Thread.AllocateNamedDataSlot(SessionStorageName);
         }
         return(Thread.GetData(storage) as ISession);
     }
 }
Example #23
0
 static HttpClientTestBase()
 {
     s_managedHandlerSlot = Thread.GetNamedDataSlot(ManagedHandlerEnvVar);
     if (s_managedHandlerSlot == null)
     {
         try
         {
             s_managedHandlerSlot = Thread.AllocateNamedDataSlot(ManagedHandlerEnvVar);
         }
         catch (ArgumentException)
         {
             s_managedHandlerSlot = Thread.GetNamedDataSlot(ManagedHandlerEnvVar);
         }
     }
     Debug.Assert(s_managedHandlerSlot != null);
 }
Example #24
0
        UserSession GetUserSession()
        {
            LocalDataStoreSlot slot = Thread.GetNamedDataSlot(SessionEnum.WebSession.UserProfiles.ToString());

            if (slot == null)
            {
                slot = Thread.AllocateNamedDataSlot(SessionEnum.WebSession.UserProfiles.ToString());
            }
            if (Thread.GetData(slot) == null)
            {
                UserSession session = new UserSession();
                session.CurrentUserLanguageID = 1;
                Thread.SetData(slot, new UserSession());
            }
            return((UserSession)Thread.GetData(slot));
        }
Example #25
0
        private ConcurrentDictionary <string, object> GetCachedData()
        {
            var slot = Thread.GetNamedDataSlot(CacheSlotName);

            if (slot == null)
            {
                slot = Thread.AllocateNamedDataSlot(CacheSlotName);
            }
            var dic = Thread.GetData(slot) as ConcurrentDictionary <string, object>;

            if (dic == null)
            {
                dic = new ConcurrentDictionary <string, object>();
                Thread.SetData(slot, dic);
            }
            return(dic);
        }
 private void Document_Move_Before(object sender, DocumentEventArgs e)
 {
     // Add track of the Document's original Parent ID so we can rebuild on that after moved.
     try
     {
         var Slot = Thread.GetNamedDataSlot("PreviousParentIDForNode_" + e.Node.NodeID);
         if (Slot == null)
         {
             Slot = Thread.AllocateNamedDataSlot("PreviousParentIDForNode_" + e.Node.NodeID);
         }
         Thread.SetData(Slot, e.Node.NodeParentID);
     }
     catch (Exception ex)
     {
         LogErrorsInSeparateThread(ex, "DynamicRouting", "Error", $"Occurred on Document Move Before for Node {e.Node.NodeAliasPath}");
     }
 }
        public void ThreadLocalStorageExample()
        {
            Thread.AllocateNamedDataSlot("Value");

            var threadLocalStorage1 = new Thread(() =>
            {
                var slotThread1 = Thread.GetNamedDataSlot("Value");
                Thread.SetData(slotThread1, 0);
                for (var count = 0; count < 5; count++)
                {
                    Thread.Sleep(2000);
                    var value = (int)Thread.GetData(slotThread1);
                    Clients.Caller.ThreadLocalStorageExample("Thread local storage 1: " + value);
                    value++;
                    Thread.SetData(slotThread1, value);
                }
            });

            var threadLocalStorage2 = new Thread(() =>
            {
                var slotThread2 = Thread.GetNamedDataSlot("Value");
                Thread.SetData(slotThread2, 0);
                for (var count = 0; count < 5; count++)
                {
                    Thread.Sleep(2000);
                    var value = (int)Thread.GetData(slotThread2);
                    Clients.Caller.ThreadLocalStorageExample("Thread local storage 2: " + value);
                    value++;
                    Thread.SetData(slotThread2, value);
                }
            });

            Clients.Caller.ThreadLocalStorageExample("Thread local storage example started.");
            threadLocalStorage1.Start();
            Thread.Sleep(12000);
            threadLocalStorage2.Start();
            Thread.Sleep(12000);
            var mainThreadSlot = Thread.GetNamedDataSlot("Value");

            Thread.SetData(mainThreadSlot, 0);
            var mainValue = (int)Thread.GetData(mainThreadSlot);

            Clients.Caller.ThreadLocalStorageExample("Thread local storage result: " + mainValue);
            Clients.Caller.ThreadLocalStorageExample("Thread local storage example ended.");
        }
Example #28
0
        private static Dictionary <Transaction, Dictionary <string, DbConnection> > GetTransactionConnectionDictionary()
        {
            string             name = "DB_Transaction_Scope";
            LocalDataStoreSlot slot = Thread.GetNamedDataSlot(name);

            if (slot == null)
            {
                slot = Thread.AllocateNamedDataSlot(name);
            }
            var transactionConnections = Thread.GetData(slot) as Dictionary <Transaction, Dictionary <string, DbConnection> >;

            if (transactionConnections == null)
            {
                transactionConnections = new Dictionary <Transaction, Dictionary <string, DbConnection> >();
                Thread.SetData(slot, transactionConnections);
            }
            return(transactionConnections);
        }
Example #29
0
            private static LocalDataStoreSlot GetSlot()
            {
                LocalDataStoreSlot slot = Thread.GetNamedDataSlot(ManagedHandlerEnvVar);

                if (slot != null)
                {
                    return(slot);
                }

                try
                {
                    return(Thread.AllocateNamedDataSlot(ManagedHandlerEnvVar));
                }
                catch (ArgumentException) // in case of a race condition where multiple threads all try to allocate the slot concurrently
                {
                    return(Thread.GetNamedDataSlot(ManagedHandlerEnvVar));
                }
            }
Example #30
0
        /// <summary>
        /// Gets a component instance from the designer.
        /// </summary>
        /// <returns>
        /// The component instance.
        /// </returns>
        public object GetComponent()
        {
            var slot = Thread.GetNamedDataSlot(name);

            if (slot == null)
            {
                slot = Thread.AllocateNamedDataSlot(name);
            }

            var instance = Thread.GetData(slot);

            if (instance == null)
            {
                instance = constructor();
                Thread.SetData(slot, instance);
            }

            return(instance);
        }