本文整理汇总了C#中ConcurrentDictionary类的典型用法代码示例。如果您正苦于以下问题:C# ConcurrentDictionary类的具体用法?C# ConcurrentDictionary怎么用?C# ConcurrentDictionary使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
ConcurrentDictionary类属于命名空间,在下文中一共展示了ConcurrentDictionary类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: SpeechService
public SpeechService()
{
this.textToSpeech = new TextToSpeech(Application.Context, this);
this.textToSpeech.SetOnUtteranceProgressListener(this);
this.inFlightSpeech = new ConcurrentDictionary<int, AsyncSubject<Unit>>();
}
示例2: BuildSerializer
public override ValueSerializer BuildSerializer(Serializer serializer, Type type,
ConcurrentDictionary<Type, ValueSerializer> typeMapping)
{
var x = new ObjectSerializer(type);
typeMapping.TryAdd(type, x);
var elementType = GetEnumerableType(type);
var arrType = elementType.MakeArrayType();
var listModule = type.Assembly.GetType("Microsoft.FSharp.Collections.ListModule");
var ofArray = listModule.GetMethod("OfArray");
var ofArrayConcrete = ofArray.MakeGenericMethod(elementType);
var ofArrayCompiled = CodeGenerator.CompileToDelegate(ofArrayConcrete, arrType);
var toArray = listModule.GetMethod("ToArray");
var toArrayConcrete = toArray.MakeGenericMethod(elementType);
var toArrayCompiled = CodeGenerator.CompileToDelegate(toArrayConcrete, type);
ValueWriter writer = (stream, o, session) =>
{
var arr = toArrayCompiled(o);
var arrSerializer = serializer.GetSerializerByType(arrType);
arrSerializer.WriteValue(stream,arr,session);
};
ValueReader reader = (stream, session) =>
{
var arrSerializer = serializer.GetSerializerByType(arrType);
var items = (Array)arrSerializer.ReadValue(stream, session);
var res = ofArrayCompiled(items);
return res;
};
x.Initialize(reader, writer);
return x;
}
示例3: GetAmicableNumbersParallelized
public static ConcurrentDictionary<int, int> GetAmicableNumbersParallelized(int n)
{
ConcurrentDictionary<int, int> amicableNumbers =
new ConcurrentDictionary<int, int>();
Parallel.For(1, n, (i) =>
{
Parallel.For(i, n, (j) =>
{
if (i != j &&
i == GetEvenDivisors(j).Sum() &&
j == GetEvenDivisors(i).Sum())
{
amicableNumbers.TryAdd(i, j);
Console.WriteLine("Found {0} and {1} using Thread {2}.",
GetEvenDivisors(i).Sum(),
GetEvenDivisors(j).Sum(),
Thread.CurrentThread.ManagedThreadId);
}
}
);
});
return amicableNumbers;
}
示例4: test3
static void test3()
{
ConcurrentDictionary<string, string> list = new ConcurrentDictionary<string, string>();
list["a"]="a";
list["b"] = "b";
Console.WriteLine(list.Count);
}
示例5: Main
public static void Main()
{
var stock = new ConcurrentDictionary<string, int>();
stock.TryAdd("jDays", 4);
stock.TryAdd("technologyhour", 3);
Console.WriteLine("No. of shirts in stock = {0}", stock.Count);
var success = stock.TryAdd("pluralsight", 6);
Console.WriteLine("Added succeeded? " + success);
success = stock.TryAdd("pluralsight", 6);
Console.WriteLine("Added succeeded? " + success);
stock["buddhistgeeks"] = 5;
//stock["pluralsight"]++; <-- not thread safe two instructions
var psStock = stock.AddOrUpdate("pluralsight", 1, (key, oldValue) => oldValue + 1);
Console.WriteLine("pluralsight new value = {0}", psStock);
Console.WriteLine("stock[pluralsight] = {0}", stock.GetOrAdd("pluralsight", 0));
int jDaysValue;
success= stock.TryRemove("jDays", out jDaysValue);
if (success) Console.WriteLine("Value removed was: " + jDaysValue);
Console.WriteLine("\r\nEnumerating:");
foreach (var keyValuePair in stock)
{
Console.WriteLine("{0}: {1}", keyValuePair.Key, keyValuePair.Value);
}
}
示例6: FileSystemRefreshableWatcher
public FileSystemRefreshableWatcher(IFileSystemWatcher watcher) : base(watcher)
{
_refreshTokenSource = new CancellationTokenSource();
_waitingThreadsEvents = new ConcurrentDictionary<Thread, ManualResetEventSlim>();
IsRefreshing = false;
_refreshLock = new object();
}
示例7: LightningEnvironment
public LightningEnvironment(string directory, EnvironmentOpenFlags openFlags)
{
if (String.IsNullOrWhiteSpace(directory))
throw new ArgumentException("Invalid directory name");
IntPtr handle = default(IntPtr);
Native.Execute(() => Native.mdb_env_create(out handle));
_shouldDispose = true;
_handle = handle;
this.Directory = directory;
_openFlags = openFlags;
_mapSize = DefaultMapSize;
_maxDbs = DefaultMaxDatabases;
_openedDatabases = new ConcurrentDictionary<string, LightningDatabase>();
_databasesForReuse = new HashSet<uint>();
ConverterStore = new ConverterStore();
var defaultConverters = new DefaultConverters();
defaultConverters.RegisterDefault(this);
}
示例8: ClusterMembership
public ClusterMembership(ClusterMembershipConfiguration config, ILogger logger)
{
lastPingTime = DateTime.UtcNow;
this.config = config;
this.logger = logger;
clusterMembers = new ConcurrentDictionary<SocketEndpoint, ClusterMemberMeta>();
}
示例9: QueryCacheManager
/// <summary>Static constructor.</summary>
static QueryCacheManager()
{
Cache = new MemoryCache(new MemoryCacheOptions());
DefaultMemoryCacheEntryOptions = new MemoryCacheEntryOptions();
CachePrefix = "Z.EntityFramework.Plus.QueryCacheManager;";
CacheTags = new ConcurrentDictionary<string, List<string>>();
}
示例10: SocketEventClient
public SocketEventClient(string id, string url)
{
this.ClientId = id;
this.Url = url;
this.eventStore = new ConcurrentDictionary<string, dynamic>();
this.locker = new Semaphore(1, 1);
}
示例11: GetColorCount
/// <summary>
/// Returns the color count from the palette of the given image.
/// </summary>
/// <param name="image">
/// The <see cref="System.Drawing.Image"/> to get the colors from.
/// </param>
/// <returns>
/// The <see cref="int"/> representing the color count.
/// </returns>
public static int GetColorCount(Image image)
{
ConcurrentDictionary<Color, Color> colors = new ConcurrentDictionary<Color, Color>();
int width = image.Width;
int height = image.Height;
using (FastBitmap fastBitmap = new FastBitmap(image))
{
Parallel.For(
0,
height,
y =>
{
for (int x = 0; x < width; x++)
{
// ReSharper disable once AccessToDisposedClosure
Color color = fastBitmap.GetPixel(x, y);
colors.TryAdd(color, color);
}
});
}
int count = colors.Count;
colors.Clear();
return count;
}
示例12: GetMetrics
public IEnumerable<JobMetric> GetMetrics(IDictionary<Guid, IDictionary<Guid, int?>> packagesWithJobsAndLastBuildNumber)
{
using (var gateway = PackageConfigurationGatewayFactory())
{
var result = new ConcurrentDictionary<string, JobMetric>();
foreach (var packagesWithJob in packagesWithJobsAndLastBuildNumber)
{
var configuration = gateway.GetPackageConfiguration(packagesWithJob.Key);
if (configuration == null || string.IsNullOrEmpty(configuration.JenkinsServerUrl))
continue;
var jobs = gateway.GetJobs(packagesWithJob.Value.Keys)
.Join(packagesWithJob.Value, j => j.ExternalId, k => k.Key,
(j, k) => new {Job = j, BuildNumber = k.Value});
JenkinsRequest.ChangeBaseUrl(configuration.JenkinsServerUrl);
JenkinsRequest.ChangeBaseUrl(configuration.JenkinsServerUrl);
Parallel.ForEach(jobs, j =>
{
var metrics = JenkinsRequest.GetJobMetrics(j.Job.Name, j.BuildNumber, configuration.TimeZone);
if (metrics == null) return;
if (!result.TryAdd(j.Job.Name, metrics))
{
Logger.ErrorFormat("Jenkins Job measurements not stored. Job={0}, Id={1}",
j.Job.Name, j.Job.ExternalId);
}
});
}
return result.Values.ToArray();
}
}
示例13: MainMethod
public void MainMethod()
{
Console.WriteLine("Concurrent Dictionary Run implementation");
ConcurrentDictionary<string, int> dictionary = new ConcurrentDictionary<string, int>();
if(dictionary.TryAdd("k1",10))
{
Console.WriteLine("Added Key k1");
}
if(dictionary.TryUpdate("k1",19,10))
{
Console.WriteLine("Updated Key k1");
}
if (dictionary.TryUpdate("k1", 19, 10))
{
Console.WriteLine("Updated Key k1");
}
else
Console.WriteLine("Failed to Update");
dictionary["k1"] = 16;
int r1 = dictionary.AddOrUpdate("k1", 2, (s, i) => i * 2);
Console.WriteLine(r1);
int r3 = dictionary.AddOrUpdate("k3", 2, (s, i) => i * 2);
Console.WriteLine(r3);
int r2 = dictionary.GetOrAdd("k2", 4);
Console.WriteLine(r2);
}
示例14: WorkContext
public WorkContext()
{
DoNotTouchAgainIfMissingReferences = new ConcurrentDictionary<int, ConcurrentSet<string>>();
CurrentlyRunningQueries = new ConcurrentDictionary<string, ConcurrentSet<ExecutingQueryInfo>>(StringComparer.OrdinalIgnoreCase);
MetricsCounters = new MetricsCountersManager();
InstallGauges();
}
示例15: Consumer
public Consumer(string groupName, ConsumerSetting setting)
{
if (groupName == null)
{
throw new ArgumentNullException("groupName");
}
GroupName = groupName;
Setting = setting ?? new ConsumerSetting();
_lockObject = new object();
_subscriptionTopics = new Dictionary<string, HashSet<string>>();
_topicQueuesDict = new ConcurrentDictionary<string, IList<MessageQueue>>();
_pullRequestDict = new ConcurrentDictionary<string, PullRequest>();
_remotingClient = new SocketRemotingClient(Setting.BrokerAddress, Setting.SocketSetting, Setting.LocalAddress);
_adminRemotingClient = new SocketRemotingClient(Setting.BrokerAdminAddress, Setting.SocketSetting, Setting.LocalAdminAddress);
_binarySerializer = ObjectContainer.Resolve<IBinarySerializer>();
_scheduleService = ObjectContainer.Resolve<IScheduleService>();
_allocateMessageQueueStragegy = ObjectContainer.Resolve<IAllocateMessageQueueStrategy>();
_logger = ObjectContainer.Resolve<ILoggerFactory>().Create(GetType().FullName);
_remotingClient.RegisterConnectionEventListener(new ConnectionEventListener(this));
if (Setting.MessageHandleMode == MessageHandleMode.Sequential)
{
_consumingMessageQueue = new BlockingCollection<ConsumingMessage>();
_consumeMessageWorker = new Worker("ConsumeMessage", () => HandleMessage(_consumingMessageQueue.Take()));
}
_messageRetryQueue = new BlockingCollection<ConsumingMessage>();
}