本文整理汇总了C#中ThreadLocal类的典型用法代码示例。如果您正苦于以下问题:C# ThreadLocal类的具体用法?C# ThreadLocal怎么用?C# ThreadLocal使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
ThreadLocal类属于命名空间,在下文中一共展示了ThreadLocal类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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)));
}
开发者ID:phmatray,项目名称:CCrossHelper,代码行数:10,代码来源:StaticRandom.cs
示例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;
}
开发者ID:tamirdresher,项目名称:ADVNet0116,代码行数:34,代码来源:Program.cs
示例3: TracePipeline
private TracePipeline(DebugContext debugContext)
{
_debugContext = debugContext;
_traceFrame = new ThreadLocal<DebugFrame>();
debugContext.DebugCallback = this;
debugContext.DebugMode = DebugMode.FullyEnabled;
}
开发者ID:TerabyteX,项目名称:main,代码行数:7,代码来源:TracePipeline.cs
示例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");
}
开发者ID:kumpera,项目名称:mono,代码行数:33,代码来源:ThreadLocalTests.cs
示例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"));
}
}
开发者ID:Wolfium,项目名称:MaxMind-DB-Reader-dotnet,代码行数:27,代码来源:PointerTest.cs
示例6: InitializeComponent
public override void InitializeComponent()
{
base.InitializeComponent();
CurrentFakeHleThreads = new ThreadLocal<HleThread>(() => new HleThread(PspEmulatorContext, new CpuThreadState(CpuProcessor)));
//throw new NotImplementedException();
//CurrentFakeHleThread = ;
}
开发者ID:shin527,项目名称:cspspemu,代码行数:7,代码来源:HleInterop.cs
示例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;
}
开发者ID:enrique-avalon,项目名称:RawRabbit,代码行数:31,代码来源:ReusableChannelFactory.cs
示例8: FairPartitionResolver
public FairPartitionResolver(IReadOnlyList<string> collectionLinks)
{
Guard.NotNull("collectionLinks", collectionLinks);
this.collectionLinks = collectionLinks;
this.random = new ThreadLocal<Random>(CreateNewRandom);
}
开发者ID:kingkino,项目名称:azure-documentdb-datamigrationtool,代码行数:7,代码来源:FairPartitionResolver.cs
示例9: Client
public HttpClient Client()
{
GatewayConfiguration = new HttpGatewayConfiguration();
_timeout = Convert.ToDouble(GatewayConfiguration.OrderServiceConfiguration.Timeout);
_client = new ThreadLocal<HttpClient>(() => CreateClient(_timeout));
return _client.Value;
}
开发者ID:iancooper,项目名称:ServiceDiscovery-Tutorial,代码行数:7,代码来源:HttpClientGateway.cs
示例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);
}
开发者ID:Originalutter,项目名称:RawRabbit,代码行数:35,代码来源:ChannelFactory.cs
示例11: ReplyAuthenticationSessionAttacher
public ReplyAuthenticationSessionAttacher(
AuthenticationSessionCache cache,
AuthenticatedServerRegistry registry)
: base(cache, registry)
{
address = new ThreadLocal<EndpointAddress>();
}
开发者ID:SystemDot,项目名称:SystemDotServiceBus,代码行数:7,代码来源:ReplyAuthenticationSessionAttacher.cs
示例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);
}
开发者ID:noahfalk,项目名称:corefx,代码行数:7,代码来源:ThreadLocalTests.cs
示例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);
}
开发者ID:noahfalk,项目名称:corefx,代码行数:29,代码来源:ThreadLocalTests.cs
示例14: EnsureInitialized
private void EnsureInitialized()
{
if (_random == null)
{
_random = new ThreadLocal<System.Random>(() => new System.Random(Seed.Value));
}
}
开发者ID:slumos,项目名称:metrics-net,代码行数:7,代码来源:ThreadLocalRandom.cs
示例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);
}
}
);
}
开发者ID:mesheets,项目名称:Theraot-CF,代码行数:29,代码来源:ThreadLocalTestsEx.cs
示例16: ThreadLocalRandom
static ThreadLocalRandom()
{
lock (Seeder)
{
Seed = new ThreadLocal<int>(() => Seeder.Next());
}
}
开发者ID:slumos,项目名称:metrics-net,代码行数:7,代码来源:ThreadLocalRandom.cs
示例17: TestBlockingQueueStress
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);
}
开发者ID:mamitko,项目名称:GZipTest,代码行数:33,代码来源:TestParallellizing.cs
示例18: OAuthServerHelper
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);
}
开发者ID:925coder,项目名称:ravendb,代码行数:34,代码来源:OAuthServerHelper.cs
示例19: IOCompletionPortTaskScheduler
/// <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();
}
}
开发者ID:bevacqua,项目名称:Swarm,代码行数:36,代码来源:IOCompletionPortTaskScheduler.cs
示例20: Run
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());
}
开发者ID:ddt626,项目名称:PLINQDemo,代码行数:34,代码来源:ParallelSpellcheckerUsingThreadLocal.cs
注:本文中的ThreadLocal类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论