public DictionariesSerialization() { _serializer = Binary.Create(new Settings { SerializationMode = Mode.Graph }); _dict = new Dictionary <int, int>(); _immDict = ImmutableDictionary <int, int> .Empty; _immSortedDict = ImmutableSortedDictionary <int, int> .Empty; _sasaTrie = Trie <int, int> .Empty; _hashMap = HashMap <int, int> .Empty; for (int i = 0; i < 10000; ++i) { _dict.Add(i, i); _immDict = _immDict.SetItem(i, i); _immSortedDict = _immSortedDict.SetItem(i, i); _sasaTrie = _sasaTrie.Add(i, i); _hashMap = _hashMap.SetItem(i, i); } _dStream = new MemoryStream(); _idStream = new MemoryStream(); _isdStream = new MemoryStream(); _sasaStream = new MemoryStream(); _hashMapStream = new MemoryStream(); _serializer.Write(_dict, _dStream); _serializer.Write(_immDict, _idStream); _serializer.Write(_immSortedDict, _isdStream); _serializer.Write(_sasaTrie, _sasaStream); _serializer.Write(_hashMap, _hashMapStream); }
/// <summary> /// Delivers the given <paramref name="message"/> to a <paramref name="destination"/>. The delivery of <paramref name="message"/> is identified by /// the given <paramref name="deliveryId"/> which must be unique in context of the sending actor. The message is /// tracked as unconfirmed message until delivery is confirmed by persisting a confirmation event /// with `persistConfirmation`, using the same `deliveryId`. /// </summary> public void Deliver(string deliveryId, object message, ActorPath destination) { unconfirmed = unconfirmed.SetItem(deliveryId, new DeliveryAttempt(deliveryId, message, destination)); if (!IsRecovering) { Send(message, destination); } }
protected override ImmutableSortedDictionary <TKey, TValue> SetValues(ImmutableSortedDictionary <TKey, TValue> values, ref ArraySegment <KeyValuePair <TKey, TValue> > newValues, ISerializationContext context) { if (newValues.Count == 1) { var pair = newValues.Singleton(); return(values.SetItem(pair.Key, pair.Value)); } return(values.SetItems(newValues)); }
/// <summary> /// TBD /// </summary> /// <param name="destination">TBD</param> /// <param name="deliveryMessageMapper">TBD</param> /// <param name="isRecovering">TBD</param> /// <exception cref="MaxUnconfirmedMessagesExceededException"> /// This exception is thrown when the actor exceeds the <see cref="MaxUnconfirmedMessages"/> count. /// </exception> public void Deliver(ActorPath destination, Func <long, object> deliveryMessageMapper, bool isRecovering) { if (_unconfirmed.Count >= MaxUnconfirmedMessages) { throw new MaxUnconfirmedMessagesExceededException( $"{_context.Self} has too many unconfirmed messages. Maximum allowed is {MaxUnconfirmedMessages}"); } long deliveryId = NextDeliverySequenceNr(); DateTime now = isRecovering ? DateTime.UtcNow - RedeliverInterval : DateTime.UtcNow; var delivery = new Delivery(destination, deliveryMessageMapper(deliveryId), now, 0); if (isRecovering) { _unconfirmed = _unconfirmed.SetItem(deliveryId, delivery); } else { Send(deliveryId, delivery, now); } }
public IPackageInfo Fetch(string packageId) { IPackageInfo package = sources.FetchPackage(packageId); if (package == null) { return(null); } packages = packages.SetItem(package.Id, package); return(package); }
public void AddOrUpdate(string configPath) { IConfig config = BuildConfig(configPath); if (config == null) { return; } string key = configPath.GetFullConsolidatedPath(); configs.SetItem(key, config); }
private void SetProject(string projectPath, bool fetch) { IProject project = BuildProject(projectPath, fetch); if (project == null) { return; } string key = projectPath.GetFullConsolidatedPath(); projects = projects.SetItem(key, project); }
private static ImmutableSortedDictionary <DateTime, State> AddOrUpdateStatesDictAndCleanOld( ImmutableSortedDictionary <DateTime, State> states, State newState, DateTime now) { var minEventTime = now - TimeSpan.FromMinutes(1); var old = states.Keys.SkipWhile(e => e < minEventTime); states = states.RemoveRange(old); if (states.TryGetValue(now, out var oldState)) { newState = new State(oldState, newState); } return(states.SetItem(now, newState)); }
public ParseResult <V> TryParseAt <V>(ICharParser <V> parser, int pos, int len) { long parserId = idgen.GetId(parser); PosLenId posLenId = new PosLenId(pos, len, parserId); if (memoTable.ContainsKey(posLenId)) { return((ParseResult <V>)memoTable[posLenId]); } else { ParseResult <V> r = parser.TryParse(this, pos, len); memoTable = memoTable.SetItem(posLenId, r); return(r); } }
public override OperationResult <TKey, TValue> Apply(ref ImmutableSortedDictionary <TKey, Sequenced <TValue> > dictionary) { if (dictionary == null) { throw new ArgumentNullException(nameof(dictionary)); } if (dictionary.ContainsKey(Key)) { var val = _sequenceId == -1 ? new Sequenced <TValue>(Value) : new Sequenced <TValue>(Value, _sequenceId); _sequenceId = val.SequenceId; dictionary = dictionary.SetItem(Key, val); return(new UpdateOperationResult <TKey, TValue>(keyNotFound: false)); } return(new UpdateOperationResult <TKey, TValue>(keyNotFound: true)); }
void Test() { ImmutableSortedDictionary <int, string> sortedDictionary = ImmutableSortedDictionary <int, string> .Empty; sortedDictionary = sortedDictionary.Add(10, "Ten"); sortedDictionary = sortedDictionary.Add(21, "Twenty-One"); sortedDictionary = sortedDictionary.SetItem(10, "Diez"); // Displays "10Diez" followed by "21Twenty-One". foreach (KeyValuePair <int, string> item in sortedDictionary) { Trace.WriteLine(item.Key + item.Value); } string ten = sortedDictionary[10]; // ten == "Diez" sortedDictionary = sortedDictionary.Remove(21); }
/// <summary> /// Increment the version for the node passed as argument. Returns a new VectorClock. /// </summary> /// <param name="node">Increment the vector clock value for a particular node.</param> /// <returns>An updated <see cref="VectorClock"/> instance.</returns> public VectorClock Increment(Node node) { var currentTimestamp = _versions.GetOrElse(node, Timestamp.Zero); return(new VectorClock(_versions.SetItem(node, currentTimestamp + 1))); }
/// <summary> /// Adds or replaces. /// </summary> /// <param name="k">Key</param> /// <param name="v">Value</param> /// <returns>New dictionary with the (key, value) pair added or replaced.</returns> public DictionaryDatum Add(Datum k, Datum v) { return(new DictionaryDatum(dict.SetItem(k, v))); }
public Tree Update(string path, TreeEntry entry) => new Tree(_items.SetItem(path, entry));
static void Main(string[] args) { // 不可变栈和队列 ImmutableStack <int> stack = ImmutableStack <int> .Empty; stack = stack.Push(13); stack = stack.Push(7); foreach (int item in stack) { Console.WriteLine(item); } int lastItem; stack = stack.Pop(out lastItem); Console.WriteLine(lastItem); // 队列和栈类似 ImmutableQueue <int> queue = ImmutableQueue <int> .Empty; queue = queue.Enqueue(13); queue = queue.Enqueue(7); // 在7之前显示13 foreach (int item in queue) { Console.WriteLine(item); } int nextItem; queue = queue.Dequeue(out nextItem); // 只显示13 Console.WriteLine(nextItem); //不可变列表 ImmutableList <int> list = ImmutableList <int> .Empty; list = list.Insert(0, 13); list = list.Insert(0, 7); // 在13之前显示7 foreach (int item in list) { Console.WriteLine(item); } list = list.RemoveAt(1); //不可变set //hash的 ImmutableHashSet <int> hashSet = ImmutableHashSet <int> .Empty; hashSet = hashSet.Add(13); hashSet = hashSet.Add(7); // 以不可预知的顺序显示7和13 foreach (int item in hashSet) { Console.WriteLine(item); } hashSet = hashSet.Remove(7); //sorted ImmutableSortedSet <int> sortedSet = ImmutableSortedSet <int> .Empty; sortedSet = sortedSet.Add(13); sortedSet = sortedSet.Add(7); // 在13之前显示7 foreach (int item in sortedSet) { Console.WriteLine(item); } int smallestItem = sortedSet[0]; // smallestItem == 7 sortedSet = sortedSet.Remove(7); //不可变Dictionary //无排序 ImmutableDictionary <int, string> dictionary = ImmutableDictionary <int, string> .Empty; dictionary = dictionary.Add(10, "Ten"); dictionary = dictionary.Add(21, "Twenty-One"); dictionary = dictionary.SetItem(10, "Diez"); // 以不可预知的顺序显示10Diez和21Twenty-One foreach (KeyValuePair <int, string> item in dictionary) { Console.WriteLine(item.Key + item.Value); } string ten = dictionary[10]; // ten == "Diez" dictionary = dictionary.Remove(21); //有排序 ImmutableSortedDictionary <int, string> sortedDictionary = ImmutableSortedDictionary <int, string> .Empty; sortedDictionary = sortedDictionary.Add(10, "Ten"); sortedDictionary = sortedDictionary.Add(21, "Twenty-One"); sortedDictionary = sortedDictionary.SetItem(10, "Diez"); // 在21Twenty-One之前显示10Diez foreach (KeyValuePair <int, string> item in sortedDictionary) { Console.WriteLine(item.Key + item.Value); } ten = sortedDictionary[10]; // ten == "Diez" sortedDictionary = sortedDictionary.Remove(21); //线程安全的字典 var cd = new ConcurrentDictionary <int, string>(); string newvalue = cd.AddOrUpdate(0, key => "Zero", (key, oldvalue) => "Zero"); bool keyExists = cd.TryGetValue(0, out string currentvalue); if (keyExists) { Console.WriteLine(currentvalue); } bool keyExisted = cd.TryRemove(0, out currentvalue); { Console.WriteLine(currentvalue); } //阻塞队列 BlockingCollection <int> blockQueue = new BlockingCollection <int>(); blockQueue.Add(7); blockQueue.Add(13); blockQueue.CompleteAdding(); //标记完成 //消费者消费 foreach (int item in blockQueue.GetConsumingEnumerable()) { Console.WriteLine(item); } // 异步队列 Channel <int> channelQueue = Channel.CreateUnbounded <int>(); //生产者代码 ChannelWriter <int> writer = channelQueue.Writer; var t = writer.WriteAsync(7); var t2 = writer.WriteAsync(13); writer.Complete(); Task.WhenAll(t.AsTask(), t2.AsTask()).Wait(); //消费者代码 ChannelReader <int> reader = channelQueue.Reader; ReaderCode(reader).Wait(); //使用TPL完成 var asyncQueue = new BufferBlock <int>(); //生产者代码 var t3 = asyncQueue.SendAsync(7); var t4 = asyncQueue.SendAsync(13); asyncQueue.Complete(); Task.WhenAll(t3, t4).Wait(); //消费者代码 TPLReaderCode(asyncQueue).Wait(); //节流队列的几种创建方式 Channel <int> cq = Channel.CreateBounded <int>(1); BufferBlock <int> b = new BufferBlock <int>(new DataflowBlockOptions { BoundedCapacity = 1 }); BlockingCollection <int> bb = new BlockingCollection <int>(boundedCapacity: 1); //采样队列的几种创建方式 cq = Channel.CreateBounded <int>(new BoundedChannelOptions(1) { FullMode = BoundedChannelFullMode.DropOldest }); //使用ActionBlock来定义阻塞异步队列 BlockAsyncQueue().Wait(); }