public void RunSimpleListThreaded() { int NUMBER_OF_ITERATIONS = 1000; int NUMBER_OF_THREADS_PER_OP = 10; int NUMBER_OF_STARTING_ITEMS = NUMBER_OF_ITERATIONS * NUMBER_OF_THREADS_PER_OP; //Change the below object from SafeList to //NonSafeList to see the test fail. ISimpleList list = new SafeList(); //Prefill the list so that we KNOW that after all additions and removals //there will be the original number of items still in the list. //This is because doing a Remove on an empty list will not reduce the count. for (int i = 0; i < NUMBER_OF_STARTING_ITEMS; i++) { list.Add(new Object()); } List<Thread> threads = new List<Thread>(); for (int k = 0; k < NUMBER_OF_THREADS_PER_OP; k++) { threads.Add(new Thread(delegate() { Thread.Sleep(10); //Allow time for other threads to start for (int i = 0; i < NUMBER_OF_ITERATIONS; i++) { list.Add(new object()); } }) ); } for (int k = 0; k < 10; k++) { threads.Add(new Thread(delegate() { Thread.Sleep(10); //Allow time for other threads to start for (int i = 0; i < NUMBER_OF_ITERATIONS; i++) { list.Remove(); } }) ); } //Start all the threads foreach (Thread t in threads) { t.Start(); } //Wait for them all to end foreach (Thread t in threads) { t.Join(); } Assert.AreEqual(list.Count, NUMBER_OF_STARTING_ITEMS); }
private static string eliminateParameterizedTypes(string s) { // find all occurrences of [...] and eliminate var res = (string)s.Clone(); var stack = new SafeList <int>(); stack.Add(res.IndexOf("[", 0)); while (stack.Count > 0) { var topIndex = stack[stack.Count - 1]; if (topIndex == -1) { break; } var nextLeft = res.IndexOf("[", topIndex + 1); var nextRight = res.IndexOf("]", topIndex + 1); if (nextLeft != -1 && nextLeft < nextRight) { stack.Add(nextLeft); continue; } res = res.Remove(topIndex, nextRight - topIndex + 1); stack.RemoveAt(stack.Count - 1); if (stack.Count == 0 && topIndex < res.Length) { stack.Add(res.IndexOf("[", topIndex)); } } return(res); }
private void ConnectClientWithNewSession(NetworkConnection networkConnection) { Logger.RegistrationLog("Client (" + networkConnection.RemoteEndPoint.ToString() + ") wants to connect "); networkConnection.ClientSession = new Session(SessionIDGenerator.GetID()); Logger.RegistrationLog("Assigned Session " + networkConnection.ClientSession.SessionID + " to Client " + networkConnection.RemoteEndPoint.ToString()); SendSessionResponse(networkConnection); ConnectionsReadyForQueingUpToMatchmaking.Add(networkConnection); AcceptedConnections.Remove(networkConnection); }
public override GuiWidget AddChild(GuiWidget childToAdd, int indexInChildrenList = -1) { if (childToAdd is IWrapChildrenSeparatly) { foreach (var child in childToAdd.Children) { addedChildren.Add(child); } } else { addedChildren.Add(childToAdd); } return(childToAdd); }
/// <summary> /// Creates a thread. /// </summary> /// <returns>ThreadId</returns> public int CreateThread() { int threadId; if (!this.DestroyedExecutionMonitorIds.TryDequeue(out threadId)) { threadId = this.ThreadExecutionMonitors.Count; this.ThreadExecutionMonitors.Add(null); } SafeDebug.Assert(this.ThreadExecutionMonitors[threadId] == null, "this.destroyedExecutionMonitorIds[threadId] == null"); SafeList <IThreadExecutionMonitor> childExecutionMonitors = new SafeList <IThreadExecutionMonitor>(2); // all callbacks foreach (var monitorFactory in this.MonitorFactories) { IThreadExecutionMonitor monitor; if (monitorFactory.TryCreateThreadMonitor(threadId, out monitor)) { childExecutionMonitors.Add(monitor); } } this.ThreadExecutionMonitors[threadId] = new ThreadExecutionMonitorMultiplexer(childExecutionMonitors); return(threadId); }
public void Set <T>(ICacheItem <T> item) { var serializedItem = new SerializedCacheItem <T>(item); _cache.Set(item.Key, serializedItem, DateTimeOffset.FromFileTime(item.ExpirationTime.ToFileTime())); _keys.Add(item.Key); }
/// <summary> /// Creates new channel with custom event handler, authenticator and options /// </summary> /// <exception cref="OperationCanceledException">Thrown when channel limit is exceeded for the server</exception> /// <exception cref="DuplicateNameException">Thrown when there is already a channel with same name</exception> public Channel CreateChannel(string name, IChannelAuthenticator authenticator, IChannelEventHandler eventHandler, IMessageDeliveryHandler deliveryHandler, ChannelOptions options) { if (Options.ChannelLimit > 0 && _channels.Count >= Options.ChannelLimit) { throw new OperationCanceledException("Channel limit is exceeded for the server"); } Channel channel = _channels.Find(x => x.Name.Equals(name, StringComparison.InvariantCultureIgnoreCase)); if (channel != null) { throw new DuplicateNameException("There is already a channel with same name: " + name); } channel = new Channel(this, options, name, authenticator, eventHandler, deliveryHandler); _channels.Add(channel); if (eventHandler != null) { _ = eventHandler.OnChannelCreated(channel); } return(channel); }
public void SynchronizedListFact() { var list = new SafeList <string>(); void AddElements() { Enumerable.Range(0, Iterations) .ToList() .ForEach(i => list.Add(i.ToString())); } var threads = new List <Thread>() { new Thread(AddElements) { Name = "1" }, new Thread(AddElements) { Name = "2" }, new Thread(AddElements) { Name = "3" }, new Thread(AddElements) { Name = "4" } }; threads.ForEach(t => t.Start()); threads.ForEach(t => t.Join()); Assert.Equal(Iterations * 4, list.Count()); }
//##################################################################################### // 작업 쓰레드용 함수 protected void AcceptThreadJob() { while (m_acceptRun) { // 보류중인 접속이 없으면 대기 while (!m_listener.Pending()) { if (m_acceptRun == false) { return; } Thread.Sleep(128); } // 접속확인 Socket newClient = m_listener.AcceptSocket(); // 클라이언트 객체 생성 if (newClient != null) { ServerVisitor client = new ServerVisitor(newClient); m_clientList.Add(client); // 이벤트 발생 WhenConnected(client); } } }
public void updateNewAbilities() { return; newAbilities.Clear(); foreach (Ability ability in abilities.Values) { if (ability.MinLevel == this.digLevel_) { newAbilities.Add(ability); } } if (abilities.Count == 1) { this.player.Reply("You can now " + abilities.First().Value.AbilityText + "! :P"); } else if (abilities.Count > 1) { string abilityText = ""; string lastAbility = ""; foreach (Ability ability in abilities.Values) { abilityText += lastAbility + ", "; lastAbility = ability.AbilityText; } abilityText = abilityText.Substring(abilityText.Length - 2); // TODO: Split long texts!... this.player.Reply("You can now " + abilityText + " and " + lastAbility + "! :O"); } }
/// <summary> /// If type is an interface, returns all concrete implementing classes /// else if type is an abstract class, returns all concrete extending classes /// </summary> /// <param name="psd"></param> /// <param name="type"></param> /// <param name="extendingClasses"></param> /// <returns></returns> public static bool TryGetExtendingClasses(PexMeStaticDatabase psd, TypeEx type, out IIndexable <TypeDefinition> extendingClasses) { //load inheritance hierarchies if not already done psd.LoadInheritanceHierarchies(); extendingClasses = null; TypeStore ts; if (!psd.TypeDictionary.TryGetValue(type.Definition, out ts)) { return(false); } SafeSet <TypeDefinition> extendingClassesSet = new SafeSet <TypeDefinition>(); CollectAllExtendingClasses(ts, extendingClassesSet); if (extendingClassesSet.Count == 0) { return(false); } var extendingClassesList = new SafeList <TypeDefinition>(); foreach (var tdef in extendingClassesSet) { extendingClassesList.Add(tdef); } extendingClasses = extendingClassesList; return(true); }
/// <summary> /// Adds the client to the queue /// </summary> public async Task <QueueSubscriptionResult> AddClient(MqClient client) { foreach (IQueueAuthenticator authenticator in Server.QueueAuthenticators) { bool allowed = await authenticator.Authenticate(this, client); if (!allowed) { return(QueueSubscriptionResult.Unauthorized); } } if (Options.ClientLimit > 0 && _clients.Count >= Options.ClientLimit) { return(QueueSubscriptionResult.Full); } QueueClient cc = new QueueClient(this, client); _clients.Add(cc); client.AddSubscription(cc); foreach (IQueueEventHandler handler in Server.QueueEventHandlers) { await handler.OnConsumerSubscribed(cc); } _ = Trigger(); OnConsumerSubscribed.Trigger(cc); return(QueueSubscriptionResult.Success); }
/// <summary> /// Add an entity to the scene. /// </summary> public T Add <T>(T entity) where T : Entity { entity.Scene = this; Entities.Add(entity); entity.Initialize(); return(entity); }
/// <summary> ///Add 的测试 ///</summary> public void AddTestHelper <ValueT>() { SafeList <ValueT> target = new SafeList <ValueT>(); // TODO: 初始化为适当的值 ValueT value = default(ValueT); // TODO: 初始化为适当的值 target.Add(value); Assert.Inconclusive("无法验证不返回值的方法。"); }
public void 繞行SafeList操作集合_不同執行緒同時對SafeList新增與刪除元素_不應擲出例外() { var safeList = new SafeList <int> { 1, 2, 3, 4, 5 }; Task.Run(() => { while (true) { safeList.Add(0); } }); Task.Run(() => { while (true) { safeList.Remove(0); } }); Task.Run(() => { while (true) { var result = safeList.FindAll(x => x < 1); } }); Task.Run(() => { while (true) { safeList.AddRange(Enumerable.Range(0, 3)); } }); Task.Run(() => { while (true) { safeList.RemoveAll(x => x < 1); } }); Task.Run(() => { while (true) { safeList.Clear(); } }); Action action = () => IterateList(safeList).Wait(); action.Should().NotThrow(); }
public void AddedElementIncludedInIteration() { IterateTrigger( list, "two", () => list.Add("new"), "zero", "one", "two", "three", "four", "new" ); }
private void StartGamesExecutionThreads() { Logger.LoadBalancerLog("Starting Games Executors according to Threadcount of CPU"); for (int id = 0; id < LogicalCoreCount; id++) { GamesExecutors.Add(new GamesExecutor(id, FrameWaitConditions[id % (int)CPULoadBalanceFactor])); ThreadStarter.ThreadpoolDebug("Games Executor Thread " + id.ToString(), GamesExecutors[id].Run); } }
private void OnSocketAccept(object sender, Socket acceptedSocket) { Logger.RegistrationLog("Client connected " + acceptedSocket.RemoteEndPoint.ToString()); TCPPacketConnection tcp = new TCPPacketConnection(acceptedSocket); NetworkConnection newNetworkConnection = new NetworkConnection(tcp); Logger.ServerLog("Adding Client to Accepted Connections"); AcceptedConnections.Add(newNetworkConnection); }
private static void AddToCulpritField(IEnumerable <Field> accessedFields, SafeList <Field> culpritFields) { foreach (var acfield in accessedFields) { if (PexMeFilter.IsTypeSupported(acfield.Type)) { culpritFields.Add(acfield); } } }
/// <summary> /// アカウントを登録します。 /// </summary> /// <param name="accountInfo">登録するアカウント情報</param> public static void RegisterAccount(AccountInfo accountInfo) { if (accountInfo == null) { throw new ArgumentNullException("accountInfo"); } accounts.Add(accountInfo); OnAccountsChanged(EventArgs.Empty); // アカウント情報のキャッシュ // Task.Factory.StartNew(() => accountInfo.UserViewModel); }
public bool AddGame(Game game) { if (StopExecutor) { return(false); } else { Games.Add(game); return(true); } }
private void CreateFireball() { var mp = InputManager.MousePosition.ToVector2(); var spawnCircle = new Circle(_wizard.Position, ProjectileCircleRadius); var pos = spawnCircle.Sample(); var dir = mp - pos; dir.Normalize(); var fb = new Fireball(pos, dir * 200f); Projectiles.Add(fb); }
public void 初始化一個SafeList並加入1個元素_加入成功_集合中應包含該元素且長度為1() { var safeList = new SafeList <int>(); var fixture = new Fixture(); var element = fixture.Create <int>(); safeList.Add(element); const int expecetedCount = 1; safeList[0].Should().Be(element); safeList.Count.Should().Be(expecetedCount); }
public override void Load() { var oemParts = StaticData.Instance.GetFiles(Path.Combine("OEMSettings", "SampleParts")); Items = new SafeList <ILibraryItem>(oemParts.Select(s => new StaticDataItem(s))); Items.Add(new GeneratorItem( () => "Set Temperature".Localize(), async() => await SetTemperatureObject3D.Create()) { Category = this.Name }); Items.Add(new GeneratorItem( () => "PLA Temperature Tower".Localize(), async() => await TemperatureTowerObject3D.Create(220)) { Category = this.Name }); Items.Add(new GeneratorItem( () => "ABS Temperature Tower".Localize(), async() => await TemperatureTowerObject3D.Create(250)) { Category = this.Name }); Items.Add(new GeneratorItem( () => "PETG Temperature Tower".Localize(), async() => await TemperatureTowerObject3D.Create(260)) { Category = this.Name }); #if DEBUG Items.Add(new GeneratorItem( () => "XY Calibration".Localize(), async() => await XyCalibrationFaceObject3D.Create()) { Category = this.Name }); #endif }
public void AddClientToQueue(NetworkConnection clientConnection, ClientInitializeGamePackage initData) { if (Matchmaking.AddRequestToQueue(clientConnection.ClientSession.SessionID, initData.GamePlayerCount, initData.PlayerTeamwish)) { m_waitingClientConnections.Add(clientConnection); SendMatchmakingStatus(clientConnection, string.Format(WAITING_IN_QUEUE, TotalPlayersOnlineCallback(), TotalPlayersSearching())); clientConnection.ConnectionDiedEvent += RemoveConnection; } else { SendMatchmakingError(clientConnection, INVALID_REQUEST); } }
private static void Accepter_ClientConnected(object sender, Socket acceptedSocket) { TCPPacketConnection connection = new TCPPacketConnection(acceptedSocket); connection.Logger = logger; _connections.Add(connection); connection.InitializeCrypto(new RSACrypto(false)); //DualConnection connection = new DualConnection(acceptedSocket, IPAddress.Any); //connection.Logger = logger; //_connections.Add(connection); //connection.Initialize(false); }
/// <summary> /// Creates new Router and adds it to server routers. /// Throws exception if name is not eligible /// </summary> public IRouter AddRouter(string name, RouteMethod method) { try { if (!Filter.CheckNameEligibility(name)) { throw new InvalidOperationException("Invalid router name"); } if (_routers.Find(x => x.Name == name) != null) { throw new DuplicateNameException(); } Router router = new Router(this, name, method); _routers.Add(router); return(router); } catch (Exception e) { SendError("ADD_ROUTER", e, $"RouterName:{name}"); throw; } }
/// <summary> /// Creates new queue in the channel /// </summary> /// <exception cref="NoNullAllowedException">Thrown when server does not have default delivery handler implementation</exception> /// <exception cref="OperationCanceledException">Thrown when queue limit is exceeded for the channel</exception> /// <exception cref="DuplicateNameException">Thrown when there is already a queue with same id</exception> public async Task <ChannelQueue> CreateQueue(ushort queueId, ChannelQueueOptions options, IMessageDeliveryHandler deliveryHandler) { if (deliveryHandler == null) { throw new NoNullAllowedException("Delivery handler cannot be null."); } //multiple queues are not allowed if (!Options.AllowMultipleQueues && _queues.Count > 0) { return(null); } //if content type is not allowed for this channel, return null if (Options.AllowedQueues != null && Options.AllowedQueues.Length > 0) { if (!Options.AllowedQueues.Contains(queueId)) { return(null); } } if (Options.QueueLimit > 0 && Options.QueueLimit >= _queues.Count) { throw new OperationCanceledException("Queue limit is exceeded for the channel"); } ChannelQueue queue = _queues.Find(x => x.Id == queueId); if (queue != null) { throw new DuplicateNameException($"The channel has already a queue with same content type: {queueId}"); } queue = new ChannelQueue(this, queueId, options, deliveryHandler); _queues.Add(queue); if (EventHandler != null) { await EventHandler.OnQueueCreated(queue, this); } return(queue); }
public void OnMatchmadeGameFound(object sender, MatchmakingManager.MatchData match) { GameNetwork newGameNetwork = new GameNetwork(MasterUDPSocket, Logger, SessionManager); Game newGame = new Game(newGameNetwork, match.MaxPlayerCount, GamesIDGenerator); foreach (MatchmakingManager.ClientData client in match.Clients) { if (!newGame.AddClient(client.m_clientConnection, client.m_request.GetPlayerPlacements())) { Logger.GamesManagerLog("The client couldn't be added to the game, either the matchmaking algorithm is flawed or the AddClient Method"); Logger.GamesManagerLog("The client consists of the following placement request" + client.m_request.GetPlayerPlacements().ToString()); Logger.GamesManagerLog("The game object looks like this: " + newGame.ToString()); throw new System.Exception("The client couldn't be added to the game, either the matchmaking algorithm is flawed or the AddClient Method"); } } GamesReadyToBeStarted.Add(newGame); }
public override void Update(GameTime gameTime) { if (InputManager.KeyPressed(Keys.Space)) { Enemies.Add(new EnemyKnight()); } if (InputManager.MousePressed()) { CreateFireball(); } base.Update(gameTime); foreach (var projectile in Projectiles) { projectile.Update(gameTime); // brute-force this for now foreach (var enemy in Enemies) { if (enemy.Bounding.Overlaps(projectile.Bounding)) { projectile.Hit(enemy); } } if (projectile.Destroyed) { Projectiles.Remove(projectile); } } foreach (var enemy in Enemies) { enemy.Update(gameTime); if (enemy.Dead) { Enemies.Remove(enemy); } } Projectiles.Commit(); Enemies.Commit(); }
/// <summary> /// Creates a thread. /// </summary> /// <returns>ThreadId</returns> public int CreateThread() { int threadId; if (!this.DestroyedExecutionMonitorIds.TryDequeue(out threadId)) { threadId = this.ThreadExecutionMonitors.Count; this.ThreadExecutionMonitors.Add(null); } SafeDebug.Assert(this.ThreadExecutionMonitors[threadId] == null, "this.destroyedExecutionMonitorIds[threadId] == null"); SafeList<IThreadExecutionMonitor> childExecutionMonitors = new SafeList<IThreadExecutionMonitor>(2); // all callbacks foreach (var monitorFactory in this.MonitorFactories) { IThreadExecutionMonitor monitor; if (monitorFactory.TryCreateThreadMonitor(threadId, out monitor)) { childExecutionMonitors.Add(monitor); } } this.ThreadExecutionMonitors[threadId] = new ThreadExecutionMonitorMultiplexer(childExecutionMonitors); return threadId; }
private void PurgeUsedRegions(bool forcePurge, SafeList<Canvas> invalidatedResources) { for(var item = _UsedRegions.First; item != null; item = item.Next) { if(!item.Value.CanvasReference.IsAlive || forcePurge) { if(forcePurge) { var context = (Canvas.ResolvedContext)item.Value.CanvasReference.Target; if(context != null) { context.BackingContext = null; invalidatedResources.Add(context.Target); } } Rectangle region = item.Value.ActualRegion; _UsedRegions.Remove(item); _FragmentedArea += region.Area; } } }
/// <summary> /// If type is an interface, returns all concrete implementing classes /// else if type is an abstract class, returns all concrete extending classes /// </summary> /// <param name="psd"></param> /// <param name="type"></param> /// <param name="extendingClasses"></param> /// <returns></returns> public static bool TryGetExtendingClasses(PexMeStaticDatabase psd, TypeEx type, out IIndexable<TypeDefinition> extendingClasses) { //load inheritance hierarchies if not already done psd.LoadInheritanceHierarchies(); extendingClasses = null; TypeStore ts; if (!psd.TypeDictionary.TryGetValue(type.Definition, out ts)) return false; SafeSet<TypeDefinition> extendingClassesSet = new SafeSet<TypeDefinition>(); CollectAllExtendingClasses(ts, extendingClassesSet); if (extendingClassesSet.Count == 0) return false; var extendingClassesList = new SafeList<TypeDefinition>(); foreach (var tdef in extendingClassesSet) { extendingClassesList.Add(tdef); } extendingClasses = extendingClassesList; return true; }
private static void AddToCulpritField(IEnumerable<Field> accessedFields, SafeList<Field> culpritFields) { foreach (var acfield in accessedFields) { if (PexMeFilter.IsTypeSupported(acfield.Type)) { culpritFields.Add(acfield); } } }
/// <summary> /// Propagates the changes made by a called method to its caller, based on the lastLoadedFields /// For example, if the called method modifies any fields, then the related parent fields in the caller method /// are marked as updated /// </summary> /// <param name="callerMStore"></param> /// <param name="calledMethodStore"></param> private void PropagateModificationsToCaller(SEMethodStore callerMStore, SEMethodStore calledMethodStore, Method calledMethod) { if (this.lastLoadedFields.Count == 0) return; //Idenitfy relevant fields from the last loadedFields SafeList<Field> fieldsProcessed = new SafeList<Field>(); Field receiverField = null; //Check whether the current method call is actually on the field previously loaded TypeEx methodDeclType; if (!calledMethod.TryGetDeclaringType(out methodDeclType)) { logger.Error("Failed to get the declaring type of the method: " + calledMethod.FullName); return; } if (methodDeclType.FullName == "System.String" || methodDeclType.FullName == "System.string") { return; //Do not process string types. } //Check whether the declaring type is in the fields list foreach (var field in this.lastLoadedFields) { var fieldType = field.Type; if (fieldType == methodDeclType || fieldType.IsAssignableTo(methodDeclType) || methodDeclType.IsAssignableTo(fieldType)) { fieldsProcessed.Add(field); receiverField = field; break; } } if (receiverField == null) { //Failed to identify the reciver field of this method return; } //Identify arguments of the current method call foreach (var argtype in calledMethod.ParameterTypes) { foreach (var field in this.lastLoadedFields) { if (field == receiverField) continue; var fieldType = field.Type; if (fieldType == argtype || fieldType.IsAssignableTo(argtype) || argtype.IsAssignableTo(fieldType)) { fieldsProcessed.Add(field); break; } } } if (calledMethodStore.DefinedFieldSet.Count == 0) { //If the called method does not define any field, all current fields are just loaded fields foreach (var field in fieldsProcessed) { callerMStore.AddToUsedList(field, this.currOffset); this.lastLoadedFields.Remove(field); } } else { //process each defined field foreach (var deffield in calledMethodStore.DefinedFieldSet.Values) { TypeEx deffieldType; if (deffield.OptionalField.TryGetDeclaringType(out deffieldType)) { //Identify the related field in the lastLoadedFields Field processedField = null; foreach (var field in fieldsProcessed) { var fieldType = field.Type; if (fieldType == deffieldType || fieldType.IsAssignableTo(deffieldType) || deffieldType.IsAssignableTo(fieldType)) { processedField = field; callerMStore.AddToDefinedList(field, this.currOffset); break; } } if (processedField != null) { fieldsProcessed.Remove(processedField); this.lastLoadedFields.Remove(processedField); } } } //Consider the remaining fields at usedfields and remove them from lastLoadedFields foreach (var field in fieldsProcessed) { callerMStore.AddToUsedList(field, this.currOffset); this.lastLoadedFields.Remove(field); } } }
public void Purge(bool isForced, SafeList<Canvas> invalidatedResources) { if(isForced) { var context = (Canvas.ResolvedContext)_CanvasContext.Target; if(context != null) { context.BackingContext = null; invalidatedResources.Add(context.Target); } _CanvasContext.Target = null; } else if(!_CanvasContext.IsAlive) { _CanvasContext.Target = null; } }