本文整理汇总了C#中ThreadLocal类的典型用法代码示例。如果您正苦于以下问题:C# ThreadLocal类的具体用法?C# ThreadLocal怎么用?C# ThreadLocal使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
ThreadLocal类属于命名空间,在下文中一共展示了ThreadLocal类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: StaticRandom
/// <summary>
/// Initializes the <see cref="StaticRandom" /> class.
/// </summary>
static StaticRandom()
{
int seed = Environment.TickCount;
ThreadLocal = new ThreadLocal<Random>(
() => new Random(Interlocked.Increment(ref seed)));
}
示例2: Main
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;
}
示例3: TracePipeline
private TracePipeline(DebugContext debugContext)
{
_debugContext = debugContext;
_traceFrame = new ThreadLocal<DebugFrame>();
debugContext.DebugCallback = this;
debugContext.DebugMode = DebugMode.FullyEnabled;
}
示例4: InitializeThrowingTest
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");
}
示例5: TestWithPointers
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"));
}
}
示例6: InitializeComponent
public override void InitializeComponent()
{
base.InitializeComponent();
CurrentFakeHleThreads = new ThreadLocal<HleThread>(() => new HleThread(PspEmulatorContext, new CpuThreadState(CpuProcessor)));
//throw new NotImplementedException();
//CurrentFakeHleThread = ;
}
示例7: GetChannel
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;
}
示例8: FairPartitionResolver
public FairPartitionResolver(IReadOnlyList<string> collectionLinks)
{
Guard.NotNull("collectionLinks", collectionLinks);
this.collectionLinks = collectionLinks;
this.random = new ThreadLocal<Random>(CreateNewRandom);
}
示例9: Client
public HttpClient Client()
{
GatewayConfiguration = new HttpGatewayConfiguration();
_timeout = Convert.ToDouble(GatewayConfiguration.OrderServiceConfiguration.Timeout);
_client = new ThreadLocal<HttpClient>(() => CreateClient(_timeout));
return _client.Value;
}
示例10: ChannelFactory
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);
}
示例11: ReplyAuthenticationSessionAttacher
public ReplyAuthenticationSessionAttacher(
AuthenticationSessionCache cache,
AuthenticatedServerRegistry registry)
: base(cache, registry)
{
address = new ThreadLocal<EndpointAddress>();
}
示例12: RunThreadLocalTest3_IsValueCreated
public static void RunThreadLocalTest3_IsValueCreated()
{
ThreadLocal<string> tlocal = new ThreadLocal<string>(() => "Test");
Assert.False(tlocal.IsValueCreated);
string temp = tlocal.Value;
Assert.True(tlocal.IsValueCreated);
}
示例13: RunThreadLocalTest4_Value
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);
}
示例14: EnsureInitialized
private void EnsureInitialized()
{
if (_random == null)
{
_random = new ThreadLocal<System.Random>(() => new System.Random(Seed.Value));
}
}
示例15: MultipleReferenceToValueTest
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);
}
}
);
}