public static T DeserializePoolElement <T>(IPool <T> pool, byte[] data) where T : ISerializable, IPoolElement, new() { var obj = pool.Get(); InternalDeserialize(ref obj, data); return(obj); }
/// <summary> /// Метод, прикрепляющий сокет клиента к управляющему объекту /// </summary> /// <param name="socket"></param> public void Attach(Socket socket) { if (socket == null) { throw new ArgumentNullException(nameof(socket)); } //проверяем сокет на признаки жизни if (!socket.Connected) { throw new InvalidOperationException("Socket is not connected!"); } lock (this) { //проверяем, чтобы 2 раза нехорошие люди не дергали этот метод if (_attached) { throw new InvalidOperationException("Socket is already attached!"); } _attached = true; //устанавливаем флаг на присоединение к сокету _readCommandBuffer = _pool.Get(); //выделяем буфер на прием _sendQueue.Clear(); //на всякий случай очищаем данные _socket = socket; //устанавливаем сокет _socket.Blocking = false; //переводим сокет в неблокирующий режим _socket.NoDelay = true; //ускоряем отправку данных _offset = 0; //устанавливаем смещение от начала буфера приема _isSendComplete = true; //устанавливаем флаг, говорящий о том, что по сокету ничего не посылали DoSocketReceive(); //начинаем операцию чтения на сокете } }
/// <summary> /// MakeFace( eOrig, fNext ) attaches a new face and makes it the left /// face of all edges in the face loop to which eOrig belongs. "fNext" gives /// a place to insert the new face in the global face list. We insert /// the new face *before* fNext so that algorithms which walk the face /// list will not see the newly created faces. /// </summary> public static void MakeFace(IPool pool, Edge eOrig, Face fNext) { var fNew = pool.Get <MeshUtils.Face>(); // insert in circular doubly-linked list before fNext var fPrev = fNext._prev; fNew._prev = fPrev; fPrev._next = fNew; fNew._next = fNext; fNext._prev = fNew; fNew._anEdge = eOrig; fNew._trail = null; fNew._marked = false; // The new face is marked "inside" if the old one was. This is a // convenience for the common case where a face has been split in two. fNew._inside = fNext._inside; // fix other edges on this face loop var e = eOrig; do { e._Lface = fNew; e = e._Lnext; } while (e != eOrig); }
/// <summary> /// ћетод, отправл¤ющий клиенту команду и утилизирующий еЄ обратно в буфер /// TODO перенести метод в IRemoteClient /// </summary> /// <param name="client"></param> /// <param name="action"></param> private void SendClientCommand(IRemoteClient client, Action <IRoomCommand> action) { IRoomCommand command = null; try { command = _pool.Get(); action(command); _log.Debug("SendCommand: " + command); client.SendCommand(command); } catch (Exception e) { _pool.Free(command); _log.Error("Error SendCommand:\n" + e.ToString()); } finally { if (command != null) { _pool.Free(command); } } }
/// <summary>执行命令</summary> /// <typeparam name="T"></typeparam> /// <param name="func"></param> /// <returns></returns> public virtual T Execute <T>(Func <RedisClient, T> func) { var client = Pool.Get(); try { var i = 0; do { try { var rs = func(client); //// 如果返回Packet,需要在离开对象池之前拷贝,否则可能出现冲突 //if ((Object)rs is Packet pk) return (T)(Object)pk.Clone(); return(rs); } catch (InvalidDataException) { if (i++ >= Retry) { throw; } } } while (true); } finally { Pool.Put(client); } }
public void Init(IPool pool) { var n = _head = pool.Get <Node>(); n._prev = n._next = n; n._key = null; }
/// <summary> /// Starts to listen /// </summary> /// <param name="config">The server config.</param> /// <returns></returns> public override bool Start(IServerConfig config) { SaeState saeState = null; try { m_ListenSocket = new Socket(this.EndPoint.AddressFamily, SocketType.Dgram, ProtocolType.Udp); m_ListenSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); m_ListenSocket.Bind(this.EndPoint); //Mono doesn't support it if (Platform.SupportSocketIOControlByCodeEnum) { uint IOC_IN = 0x80000000; uint IOC_VENDOR = 0x18000000; uint SIO_UDP_CONNRESET = IOC_IN | IOC_VENDOR | 12; byte[] optionInValue = { Convert.ToByte(false) }; byte[] optionOutValue = new byte[4]; m_ListenSocket.IOControl((int)SIO_UDP_CONNRESET, optionInValue, optionOutValue); } saeState = m_SaePool.Get(); var sae = saeState.Sae; sae.UserToken = saeState; sae.RemoteEndPoint = m_AnyEndPoint; sae.Completed += new EventHandler <SocketAsyncEventArgs>(eventArgs_Completed); if (!m_ListenSocket.ReceiveFromAsync(sae)) { eventArgs_Completed(this, sae); } return(true); } catch (Exception e) { if (saeState != null) { saeState.Sae.Completed -= new EventHandler <SocketAsyncEventArgs>(eventArgs_Completed); m_SaePool.Return(saeState); } OnError(e); return(false); } }
public Pooled <T> Get(TParam param = default) { lock (_lock) { var polled = _source.Get(param); return(new Pooled <T>(this, polled.Item)); } }
private void EntityUpdate(EntityNotification notification) { var entity = entities.FirstOrDefault(e => e.Id == notification.EntityId); if (entity == null) { var entityNotification = entityNotificationPool.Get(); entityNotification.EntityId = notification.EntityId; entityNotification.Type = EntityNotification.ActionType.Request; ResourceManager.UpdateHub.Push(entityNotification, DefaultChannels.Network); entityNotification.Release(); } else { entity.Update(notification.Notification); } }
public static T Get() { if (pool == null) { pool = new Pool(8); } return(pool.Get()); }
public static PoolElementUsageHandler <T> Use <T>(this IPool <T> pool, out T element) { if (pool is null) { throw new NullReferenceException(nameof(pool)); } element = pool.Get(); return(new PoolElementUsageHandler <T>(pool, element)); }
// Update is called once per frame void Update() { spawnTimer += Time.deltaTime; if (spawnTimer >= spawnTime) { spawnTimer = 0f; IPoolObject <GameObject> poolObject = pool.Get(); StartCoroutine(UpdateInstance(poolObject, Random.Range(destroyTimeMin, destroyTimeMax))); } }
public static void Pool_NotNullElement_Feed16 <T>(IPool <T> pool) { const int feed = 16; var count = pool.GetCount(); for (var i = 0; i < count + feed; i++) { Assert.IsNotNull(pool.Get()); } }
public Task Close(CancellationToken cancellation) { var token = new PooledToken <bool>(_pool.Get()); var e = token.SocketAsyncEventArgs; e.Completed += CloseCompleted; try { if (!_socket.DisconnectAsync(e)) { CloseCompleted(_socket, e); } } catch (Exception ex) { ClearClose(e); token.TaskCompletionSource.SetException(ex); } return(token.Task); }
/// <summary> /// 发送一条弹幕 /// </summary> public int Send(Danmaku danmaku) { if (DanmakuViewPool == null) { throw new ArgumentNullException("Danmaku view pool is null. Did you call init() first?"); } DanmakuView view = DanmakuViewPool.Get(); if (view == null) { MeVisual.Warn(TAG, "show: Too many danmaku, discard"); return(RESULT_FULL_POOL); } if (DanmakuContainer == null || DanmakuContainer.Get() == null) { MeVisual.Warn(TAG, "show: Root view is null."); return(RESULT_NULL_ROOT_VIEW); } view.SetDanmaku(danmaku); // 字体大小 int textSize = danmaku.Size; view.SetTextSize(ComplexUnitType.Px, textSize); // 字体颜色 try { var color = Color.ParseColor(danmaku.Color); view.SetTextColor(color); } catch { view.SetTextColor(Color.White); } // 计算弹幕距离顶部的位置 int marginTop = PositionCalculator.GetMarginTop(view); if (marginTop == -1) { // 屏幕放不下了 MeVisual.Debug(TAG, "send: screen is full, too many danmaku [" + danmaku + "]"); return(TOO_MANY_DANMAKU); } FrameLayout.LayoutParams p = (FrameLayout.LayoutParams)view.LayoutParameters; if (p == null) { p = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.WrapContent); } p.TopMargin = marginTop; view.LayoutParameters = p; view.SetMinHeight((int)(Config.LineHeight * 1.35)); view.Show(DanmakuContainer.Get(), GetDisplayDuration(danmaku)); return(RESULT_OK); }
/// <summary>访问地址获取字符串</summary> /// <param name="address"></param> /// <returns></returns> public static async Task <String> GetStringAsync(String address) { var client = Pool.Get(); try { return(await client.DownloadStringAsync(address)); } finally { Pool.Put(client); } }
=> base.Deserialize(reader); // Entity public override void OnUpdate(SerializableNotification notification) { base.OnUpdate(notification); var entityNotification = entityNotificationPool.Get(); entityNotification.Entity = this; entityNotification.Type = EntityNotification.ActionType.Update; entityNotification.Notification = notification as PropertyChangedNotification; Simulation?.OnUpdate(entityNotification); entityNotification.Release(); }
private void OnSessionStarting() { try { var bufferState = m_BufferStatePool.Get(); OnReceiveStarted(); var buffer = bufferState.Buffer; m_Stream.BeginRead(buffer, 0, buffer.Length, OnStreamEndRead, bufferState); } catch (Exception e) { LogError(e); OnReceiveError(CloseReason.SocketError); return; } if (!m_IsReset) { StartSession(); } }
public void Spawn(int textureNum, Vector2 position, Vector2 Velocity, Vector2 Acceleration, float angle, float angularVelocity, float size, float sizeVelocity, int timeLife, Vector4 Color, float alphaVelocity) { if (Material == null || !Material.Textures.ContainsKey("Albedo")) { return; } Particle2D p = particlePool2D.Get(); p.Initialization(Material.Textures["Albedo"], textureNum, width, height, position, Velocity, Acceleration, angle, angularVelocity, size, sizeVelocity, timeLife, Color, alphaVelocity); particles.Add(p); }
public void Run() { _tcpListener.Start(100); //устанавливаем небольшую очередь для сокетов ожидающих подключения while (_mainApp.IsRunnnig) { //получаем свободного клиента var remotClient = _pool.Get(); //подключаем клиента к сокету remotClient.Attach(_tcpListener.AcceptSocket()); //запускаем клиента в менеджер комнат _roomManager.AttachClient(remotClient); } }
public void Init(IPool pool) { var v = _vHead = pool.Get <MeshUtils.Vertex>(); var f = _fHead = pool.Get <MeshUtils.Face>(); var pair = MeshUtils.EdgePair.Create(pool); var e = _eHead = pair._e; var eSym = _eHeadSym = pair._eSym; v._next = v._prev = v; v._anEdge = null; f._next = f._prev = f; f._anEdge = null; f._trail = null; f._marked = false; f._inside = false; e._next = e; e._Sym = eSym; e._Onext = null; e._Lnext = null; e._Org = null; e._Lface = null; e._winding = 0; e._activeRegion = null; eSym._next = eSym; eSym._Sym = e; eSym._Onext = null; eSym._Lnext = null; eSym._Org = null; eSym._Lface = null; eSym._winding = 0; eSym._activeRegion = null; }
public virtual void Initialize(IAppSession appSession) { AppSession = appSession; DataProcessor = appSession.CreatePipelineProcessor(); Config = appSession.Config; SyncSend = Config.SyncSend; m_SendingQueuePool = ((SocketServerBase)((ISocketServerAccessor)appSession.AppServer).SocketServer).SendingQueuePool; SendingQueue queue = m_SendingQueuePool.Get(); m_SendingQueue = queue; queue.StartEnqueue(); }
public static void Pool_TotalCount_Cycles3 <T>(IPool <T> pool) { const int feed = 2, cycles = 3; var count = pool.GetCount(); var iterations = (count + feed) * cycles; for (var i = 0; i < iterations; i++) { var obj = pool.Get(); pool.Return(obj); } Assert.IsTrue(iterations < pool.GetCount()); }
public Node InsertBefore(IPool pool, Node node, TValue key) { do { node = node._prev; } while (node._key != null && !_leq(node._key, key)); var newNode = pool.Get <Node>(); newNode._key = key; newNode._next = node._next; node._next._prev = newNode; newNode._prev = node; node._next = newNode; return(newNode); }
/// <summary> /// ћетод, создающий новую комнату /// </summary> /// <param name="roomId"></param> /// <returns></returns> private IRoomChannel CreateRoom(string roomId) { lock (_channels) { IRoomChannel roomChannel; if (!_channels.TryGetValue(roomId, out roomChannel)) { roomChannel = _poolChannels.Get(); roomChannel.RoomId = roomId; roomChannel.LastClientAccess = DateTime.Now; _channels[roomId] = roomChannel; _log.Info("Create roomId: " + roomId); } return(roomChannel); } }
private void AddContourInternal(IList <ContourVertex> vertices, ContourOrientation forceOrientation) { if (_mesh == null) { _mesh = _pool.Get <Mesh>(); } bool reverse = false; if (forceOrientation != ContourOrientation.Original) { var area = SignedArea(vertices); reverse = (forceOrientation == ContourOrientation.Clockwise && area < 0.0f) || (forceOrientation == ContourOrientation.CounterClockwise && area > 0.0f); } MeshUtils.Edge e = null; for (int i = 0; i < vertices.Count; ++i) { if (e == null) { e = _mesh.MakeEdge(_pool); _mesh.Splice(_pool, e, e._Sym); } else { // Create a new vertex and edge which immediately follow e // in the ordering around the left face. _mesh.SplitEdge(_pool, e); e = e._Lnext; } int index = reverse ? vertices.Count - 1 - i : i; // The new vertex is now e._Org. e._Org._coords = vertices[index].Position; e._Org._data = vertices[index].Data; // The winding of an edge says how the winding number changes as we // cross from the edge's right face to its left face. We add the // vertices in such an order that a CCW contour will add +1 to // the winding number of the region inside the contour. e._winding = 1; e._Sym._winding = -1; } }
private static List <HexCell> GetVisibleCells(IViewer viewer) { List <HexCell> visibleCells = m_listPool.Get(); PriorityQueue <HexCell> openSet = m_pqPool.Get(); HashSet <HexCell> closedSet = m_hashSetPool.Get(); Dictionary <HexCell, int> distances = m_mapPool.Get(); openSet.Add(viewer.Location, 0); distances[viewer.Location] = 0; while (!openSet.IsEmpty()) { HexCell current = (HexCell)openSet.Poll(); // Can never be empty optional closedSet.Add(current); visibleCells.Add(current); for (HexDirection dir = HexDirection.NE; dir <= HexDirection.NW; dir++) { HexCell neighbor = current.GetNeighbor(dir); if (neighbor == null || closedSet.Contains(neighbor)) { continue; } if (!viewer.CanSee(neighbor)) { continue; } distances[neighbor] = distances[current] + 1; if (!openSet.Update(neighbor, distances[neighbor])) { openSet.Add(neighbor, distances[neighbor]); } } } m_pqPool.Restore(openSet); m_hashSetPool.Restore(closedSet); m_mapPool.Restore(distances); return(visibleCells); }
/// <summary> /// ћетод считывает команду из переданного массива и возвращает оставшеес¤ количество байт. /// ≈сли в буфере содержитс¤ частична¤ команда, то возвращаетс¤ null /// </summary> /// <param name="buffer">ћассив байт</param> /// <param name="startIndex">—тартовый индекс</param> /// <param name="length">ƒлина масива</param> /// <param name="finishIndex">»ндекс, с которого начинаетс¤ нова¤ команда</param> /// <returns> оманда, или null, если в массиве не хранитьс¤ ни одной целой команды</returns> public IRoomCommand FromBuffer(byte[] buffer, int startIndex, int length, out int finishIndex) { if (buffer == null) { throw new ArgumentNullException(nameof(buffer)); } finishIndex = length; for (var i = startIndex; i < length; ++i) { //ищем разделитель команды if (buffer[i] == EndDelimiter) { finishIndex = i + 1; //остаток байт - это текущий индекс + 1 байт(разделитель команды) //превращаем массив байт в строку и отдел¤ем заголовок от хвоста с данными. var values = Encoding.UTF8.GetString(buffer, startIndex, i - startIndex).Split('|'); //получаем команду и записываем в неЄ заголовок var command = _commandPool.Get(); command.Command = values[0]; //начинаем сканировать блоки с данными (обычно это только 1 блок) for (var j = 1; j < values.Length; ++j) { //пропускаем пустые секции if (string.IsNullOrEmpty(values[j])) { continue; } //–аздел¤ем текстовый блок на пары - ключ + значение var commands = values[j].Split('^'); command.Data.Add(commands[0], commands[1]); } return(command); } } return(null); }
/// <summary> /// MakeVertex( eOrig, vNext ) attaches a new vertex and makes it the /// origin of all edges in the vertex loop to which eOrig belongs. "vNext" gives /// a place to insert the new vertex in the global vertex list. We insert /// the new vertex *before* vNext so that algorithms which walk the vertex /// list will not see the newly created vertices. /// </summary> public static void MakeVertex(IPool pool, Edge eOrig, Vertex vNext) { var vNew = pool.Get<MeshUtils.Vertex>(); // insert in circular doubly-linked list before vNext var vPrev = vNext._prev; vNew._prev = vPrev; vPrev._next = vNew; vNew._next = vNext; vNext._prev = vNew; vNew._anEdge = eOrig; // leave coords, s, t undefined // fix other edges on this vertex loop var e = eOrig; do { e._Org = vNew; e = e._Onext; } while (e != eOrig); }
/// <summary> /// ћетод возвращает кортеж, состо¤щий из ссылки на массив и количества записанных в массив байт. /// ¬озвращенный массив нужно будет передать обратно в IPool<bytes[]>, так как он беретс¤ из пула /// </summary> /// <param name="command">“ранслируема¤ команда</param> /// <returns>ћассив бйат и количество записанных в него байт, начина¤ с индекса 0</returns> public Tuple <byte[], int> ToBuffer(IRoomCommand command) { if (command == null) { throw new ArgumentNullException(nameof(command)); } var sb = _stringPool.Get(); //записываем заголовок команды sb.Append(command.Command); sb.Append("|"); foreach (var pair in command.Data) { //записываем значени¤ из команды sb.Append(pair.Key); sb.Append("^"); sb.Append(pair.Value); sb.Append("|"); } //добавл¤ем хвост sb.Append('\0'); //сохран¤ем команду в строке var value = sb.ToString(); //отдаем обратно билдер sb.Length = 0; _stringPool.Free(sb); //записываем в выделенный буффер данные var buffer = _bytesPool.Get(); var length = Encoding.UTF8.GetBytes(value, 0, value.Length, buffer, 0); return(new Tuple <byte[], int>(buffer, length)); }