public AsyncReqReplyServiceSpecs() { Reply = string.Empty; Replied = new ManualResetEvent(false); Console.WriteLine("Start client fiber"); Func <byte[], string> unmarshaller = x => Encoding.Unicode.GetString(x); Func <string, byte[]> marshaller = x => Encoding.Unicode.GetBytes(x); ServerFiber = PoolFiber.StartNew(); ServerContext = NetMQContext.Create(); Service = new AsyncRequestHandlerSocket <string, string>(ServerContext, "tcp://localhost:9997", unmarshaller, marshaller); Service.SetRequestHandler(ServerFiber, request => request.Reply(request.Request.ToUpper())); Console.WriteLine("Start service"); ClientFiber = StubFiber.StartNew(); ClientContext = NetMQContext.Create(); Client = new AsyncRequestSocket <string, string>(ClientContext, "tcp://localhost:9997", marshaller, unmarshaller); Console.WriteLine("Start client"); }
/// <summary> /// Construct new instance. /// </summary> /// <param name="keyResolver"></param> /// <param name="target"></param> /// <param name="fiber"></param> /// <param name="flushIntervalInMs"></param> public KeyedBatchSubscriber(Converter <T, K> keyResolver, Action <IDictionary <K, T> > target, IFiber fiber, int flushIntervalInMs) { _keyResolver = keyResolver; _fiber = fiber; _target = target; _intervalInMs = flushIntervalInMs; }
/// <summary> /// Sets a new fiber. /// All queued actions will be rerouted to that fiber. /// Can be called from anywhere except from another Executor queud action. /// Blocks until the current execution of queued actions is not finished. /// </summary> public void AcquireForNewFiber(IFiber fiber) { if (fiber == null) { throw new ArgumentNullException("fiber"); } if (_executingEntityFiberManager != null && _executingEntityFiberManager != this) { throw new InvalidOperationException("Can't call this method on from queued actions on another instance"); } lock (_executionLock) //lock (_enqueueLock) { if (_currentFiber == fiber) { return; } var fiberLocal = _currentFiber = fiber; Thread.MemoryBarrier(); // do not reorder! if (_actions != null) { fiberLocal.Enqueue(() => Execute(fiberLocal)); } } }
public TimerAction(IFiber fiber, Action action, TimeSpan dueTime, TimeSpan interval) { _action = action; _interval = interval; _timer = new Timer(x => ExecuteOnTimerThread(fiber), null, dueTime, interval); fiber.Add(this); }
public TimerAction(IFiber fiber, Action action, TimeSpan dueTime) { _action = action; _interval = TimeSpan.FromMilliseconds(-1); _timer = new Timer(x => ExecuteOnTimerThread(fiber), null, dueTime, _interval); fiber.Add(this); }
/// <summary> /// Constructs a new ActorContext. /// </summary> /// <param name="system">the ActorSystem within which the actor is created</param> /// <param name="actorType">the Type of the actor</param> /// <param name="actor">the Actor to create</param> /// <param name="name">the string name to give the Actor</param> /// <param name="props">the Props to pass individually as class arguments</param> /// <param name="parent">the ActorRef of the parent of the Actor being created</param> /// <param name="parentPath">the ActorPath of the Actor being created</param> /// <param name="suspended">the bool indicating whether the actor is being created as suspended</param> /// <param name="channel">the IChannel the actor will use</param> /// <param name="fiber">the IFiber the actor will use</param> internal ActorContext( ActorSystem system, Type actorType, Actor actor, string name, Props props, ActorRef parent, ActorPath parentPath, bool suspended, IChannel<Delivery> channel, IFiber fiber) { Actor = actor; Actor.InternalContext = this; Channel = channel; Fiber = fiber; Children = new List<ActorRef>(0); Parent = parent; Path = parentPath.WithName(name); Props = props; Receivers = new Stack<Receive>(1); Self = new ActorRef(this); Sender = ActorRef.NoSender; _Suspended = suspended; System = system; _Terminated = false; Type = actorType; Start(); }
/// <summary> /// Initializes a new instance of the <see cref = "ClientInterestArea" /> class. /// </summary> /// <param name = "peer"> /// The peer. /// </param> /// <param name = "id"> /// The id for this interest area. /// Unique per <see cref = "Actor" />. /// </param> /// <param name = "world"> /// The <see cref = "IWorld" /> this interest area is watching. /// </param> /// <param name = "fiber"> /// The fiber this intereast receives events on. /// </param> public ClientInterestArea(PeerBase peer, byte id, IWorld world, IFiber fiber) : base(id, world) { this.peer = peer; this.eventChannelSubscriptions = new Dictionary<Item, IDisposable>(); this.fiber = fiber; }
public static void TestBatchingWithKey(IFiber fiber) { using (fiber) using (var reset = new ManualResetEvent(false)) { var counter = new Channel <int>(); void Cb(IDictionary <string, int> batch) { if (batch.ContainsKey("9")) { reset.Set(); } } string KeyResolver(int x) => x.ToString(); //disposed with fiber counter.SubscribeToKeyedBatch(fiber, KeyResolver, Cb, TimeSpan.FromMilliseconds(1)); for (int i = 0; i < 10; i++) { counter.Publish(i); } Assert.IsTrue(reset.WaitOne(10000, false)); } }
public static void Reset <C>(this IFiber <C> fiber) { while (fiber.Frames.Count > 0) { fiber.Done(); } }
public Form1() { InitializeComponent(); log4net.Config.XmlConfigurator.Configure(); textBox1.Text = ConfigurationManager.AppSettings["Path"]; _application = new Application(ApplicationName); _workerFiber = new PoolFiber(); _workerFiber.Start(); _importar = new Channel<string>(); _importar.Subscribe(_workerFiber, Work); _notificationType = new NotificationType(SampleNotificationType, "Sample Notification"); _growl = new GrowlConnector { EncryptionAlgorithm = Cryptography.SymmetricAlgorithmType.AES }; _growl.NotificationCallback += GrowlNotificationCallback; _growl.Register(_application, new[] { _notificationType }); folderWatch.Created += FolderWatchCreated; folderWatch.Renamed += FolderWatchRenamed; folderWatch.Deleted += FolderWatchDeleted; InitDatabase(); if (!_autostart) return; Operar(true,true); }
void Execute(IFiber currentFiber) { lock (_executionLock) { if (currentFiber != _currentFiber) { return; // replaced } var actions = Interlocked.Exchange(ref _actions, null); if (actions == null) { return; } if (_executingEntityFiberManager != null) { throw new InvalidOperationException("Already in execution process"); } _executingEntityFiberManager = this; try { actions(); } finally { _executingEntityFiberManager = null; } } }
// ReSharper disable once UnusedMember.Local private IDisposable SubscribeToChannel <T>(IFiber fiber, IHandle <T> receive) { Type type = typeof(T); IChannel <T> channel = (IChannel <T>)_channels.GetOrAdd(type, _ => new Channel <T>()); return(channel.Subscribe(fiber, receive.Handle)); }
private void ReleaseForDisposedFiberInternal(IFiber fiber) { if ((_executingEntityFiberManager != null && _executingEntityFiberManager != this) || !Monitor.TryEnter(_executionLock, 1)) { _applicationFiber.Enqueue(() => ReleaseForDisposedFiberInternal(fiber)); return; } try { //lock (_enqueueLock) //{ if (_currentFiber != fiber) { return; } _currentFiber = null; Thread.MemoryBarrier(); // do not reorder! if (_actions != null) { _applicationFiber.Enqueue(() => Execute(null)); } //} } finally { Monitor.Exit(_executionLock); } }
/// <summary> /// Subscribe to a port but only consume the last msg per interval /// </summary> /// <typeparam name="T"></typeparam> /// <param name="port"></param> /// <param name="fiber"></param> /// <param name="receive"></param> /// <param name="interval"></param> /// <returns></returns> public static IDisposable SubscribeToLast <T>(this IFiber fiber, ISubscriberPort <T> port, Action <T> receive, TimeSpan interval) { return(new LastSubscriber <T>(port, fiber, interval, receive)); }
public ItemSetSpawnController(ISessings settings, [NotNull] LootableFactoryDelegate lootableFactory, IFiber fiber) { _lootableFactory = lootableFactory; _fiber = fiber; _settings = settings; }
private void RunMult(IFiberFactory factory, Func <IChannel <int> > queueFactory, int count, int wait1) { using AutoResetEvent wait = new AutoResetEvent(false); int hCount = 0; void Handler(int s) { int c = Interlocked.Increment(ref hCount); if (c == OperationsPerInvoke) { wait.Set(); } NOP(wait1 / 1000.0); } using IChannel <int> queue = queueFactory(); using IDisposable fibers = new Disposables(Enumerable.Range(0, count).Select(x => { IFiber fiber = factory.CreateFiber(); IDisposable sub = queue.Subscribe(fiber, Handler); return(fiber); })); for (int j = 1; j <= OperationsPerInvoke; j++) { queue.Publish(j); } WaitHandle.WaitAny(new WaitHandle[] { wait }); }
public static IWait <C> Wait <C, T>(this IFiber <C> fiber, Rest <C, T> resumeHandler) { var wait = fiber.NextWait <T>(); wait.Wait(resumeHandler); return(wait); }
protected Importar() { _cola = new PoolFiber(); _channel=new Channel<string>(); _cola.Start(); _channel.Subscribe(_cola, MoverArchivo); }
protected Importar() { _cola = new PoolFiber(); _channel = new Channel <string>(); _cola.Start(); _channel.Subscribe(_cola, MoverArchivo); }
public static IMessageProcessingPipeBuilder UseFiber(this IMessageProcessingPipeBuilder builder, IFiber fiber, Func<IMessageProcessingLockConfigBuilder, IMessageProcessingLockConfigBuilder> lockConfigurator = null) { IMessageProcessingLockConfig lockConfig = lockConfigurator != null ? lockConfigurator(new MessageProcessorLockConfig()).Build() : new MessageProcessorLockConfig(); var mp = new FiberedMessageProcessor(fiber, lockConfig); return builder.Use(next => context => mp.Process(next, context)); }
public void Stop() { try { if (mStarted) { log.InfoFormat("Updater stop!"); if (mLoop != null) { mLoop.Dispose(); mLoop = null; } lock (fiberLock) { if (mFiber != null) { mFiber.Dispose(); mFiber = null; } } mStarted = false; m_UpdateOnceCalled = false; } } catch (Exception exception) { mLoop = null; mFiber = null; mStarted = false; m_UpdateOnceCalled = false; log.ErrorFormat(exception.Message); log.ErrorFormat(exception.StackTrace); } }
public QueueConsumer(IFiber target, Action <TMsg> callback, QueueChannel3 <TMsg> eventChannel) { _target = target; _callback = callback; _eventChannel = eventChannel; _cache = ConsumeNext; }
public static IRequestPort <TRq, TRp> NewRequestPort <TRq, TRp>(this IFiber fiber, Action <IRequest <TRq, TRp> > onEvent) { var channel = new RequestChannel <TRq, TRp>(); channel.SetRequestHandler(fiber, onEvent); return(channel); }
public LunchFilter(IFiber fiber, ISubscriber<SimpleYouTubeClip> input, IPublisher<SimpleYouTubeClip> output) { this.output = output; this.subscription = input.Subscribe(fiber, NewClip); }
/// <summary> /// Construct new instance. /// </summary> /// <param name="keyResolver"></param> /// <param name="target"></param> /// <param name="fiber"></param> /// <param name="intervalInMs"></param> public KeyedBatchSubscriber(Converter <T, TK> keyResolver, Action <IDictionary <TK, T> > target, IFiber fiber, long intervalInMs) { _keyResolver = keyResolver; _fiber = fiber; _target = target; _intervalInMs = intervalInMs; }
public static IPublisherPort <T> NewPublishPort <T>(this IFiber fiber, Action <T> onEvent) { var channel = new Channel <T>(); channel.Subscribe(fiber, onEvent); return(channel); }
public static void InOrderExecution(IFiber fiber) { using (fiber) using (var reset = new AutoResetEvent(false)) { int count = 0; var result = new List <int>(); void Command() { result.Add(count++); if (count == 100) { reset.Set(); } } for (int i = 0; i < 100; i++) { fiber.Enqueue(Command); } Assert.IsTrue(reset.WaitOne(10000, false)); Assert.AreEqual(100, count); } }
public static void TestBatching(IFiber fiber) { using (fiber) using (var reset = new ManualResetEvent(false)) { var counter = new Channel <int>(); int total = 0; void Cb(IList <int> batch) { total += batch.Count; if (total == 10) { reset.Set(); } } counter.SubscribeToBatch(fiber, Cb, TimeSpan.FromMilliseconds(1)); for (int i = 0; i < 10; i++) { counter.Publish(i); } Assert.IsTrue(reset.WaitOne(10000, false)); } }
public FiberKeyedCollection(Func <T, TKey> keyGen, IExecutor executor = null) { _keyGen = keyGen; _fiber = new Fiber(executor); _channel.ReplyToPrimingRequest(_fiber, Reply); _request.SetRequestHandler(_fiber, OnRequest); }
///<summary> /// Subscribes for an initial snapshot and then incremental update. ///</summary> ///<param name="fiber">the target executor to receive the message</param> ///<param name="receive"></param> ///<param name="receiveSnapshot"> </param> public IDisposable Subscribe(IFiber fiber, Action <T> receive, Action <TSnapshot> receiveSnapshot) { var primedSubscribe = new SnapshotRequest(fiber, _updatesChannel, receive, receiveSnapshot); _requestChannel.SendRequest(null, fiber, x => primedSubscribe.Publish(x)); return(primedSubscribe); }
public IDisposable SendRequest(TRequest request, IFiber fiber, Action <TReply> onReply) { AsyncChannelRequest channelRequest = new AsyncChannelRequest(fiber, request, onReply); _requestChannel.Publish(channelRequest); return(new Unsubscriber(channelRequest, fiber)); }
/// <summary> /// New instance. /// </summary> /// <param name="target"></param> /// <param name="fiber"></param> /// <param name="flushIntervalInMs"></param> public LastSubscriber(Action <T> target, IFiber fiber, int flushIntervalInMs) { _batchLock = new object(); _fiber = fiber; _target = target; _intervalInMs = flushIntervalInMs; }
public IFiber Start() { IFiber fiber = Build(); fiber.Start(); return(fiber); }
public void OnlyOneConsumer() { using (var queues = new Disposables()) { IChannel <int> channel = new QueueChannel <int>(); ConcurrentBag <int> results = new ConcurrentBag <int>(); void OnReceive(int message) { results.Add(message); } //Init executing Fibers for (int i = 0; i < 10; i++) { IFiber threadFiber = ThreadFiber.StartNew(); queues.Add(threadFiber); channel.Subscribe(threadFiber, OnReceive); } //Push messages for (int i = 0; i < 1000000; i++) { channel.Publish(i); } Thread.Sleep(100); Assert.AreEqual(1000000, results.Count); var r1 = results.OrderBy(x => x).ToArray(); for (int i = 0; i < 1000000; i++) { Assert.AreEqual(i, r1[i]); } } }
public void SingleConsumer() { int oneConsumed = 0; using (IFiber one = PoolFiber.StartNew()) using (var reset = new AutoResetEvent(false)) { var channel = new QueueChannel <int>(); void OnMsg(int obj) { oneConsumed++; if (oneConsumed == 20) { reset.Set(); } } channel.Subscribe(one, OnMsg); for (int i = 0; i < 20; i++) { channel.Publish(i); } Assert.IsTrue(reset.WaitOne(10000, false)); } }
public void SingleConsumerWithException() { var failed = new List <Exception>(); var exec = new ExceptionHandlingExecutor(failed.Add); using (IFiber one = PoolFiber.StartNew(exec)) using (var reset = new AutoResetEvent(false)) { var channel = new QueueChannel <int>(); void OnMsg(int num) { if (num == 0) { throw new Exception(); } reset.Set(); } channel.Subscribe(one, OnMsg); channel.Publish(0); channel.Publish(1); Assert.IsTrue(reset.WaitOne(10000, false)); Assert.AreEqual(1, failed.Count); } }
public void Dispose() { if (executionFiber != null) { executionFiber.Dispose(); executionFiber = null; } }
public void Dispose() { if (_executionFiber != null) { _executionFiber.Dispose(); _executionFiber = null; } }
protected override void SetUp() { this.mockModel = base.CreateMock<IBurritoDayModel>(); this.mockView = base.CreateMock<IBurritoDayView>(); this.fiber = new StubFiber() { ExecutePendingImmediately = true }; new BurritoDayPresenter(this.mockModel.Object, this.mockView.Object, this.fiber); }
public BurritoDayModel(IFiber fiber, IWebClient client) { this.fiber = fiber; this.client = client; this.fiber.ScheduleOnInterval(this.PollState, 0, (long)this.interval.TotalMilliseconds); }
public Window1() { InitializeComponent(); fiber = new DispatcherFiber(Dispatcher); fiber.Start(); channels.TimeUpdate.SubscribeToLast(fiber, OnTimeUpdate, 0); new UpdateController(channels); }
public HttpRequestQueue() { this.QueueState = HttpRequestQueueState.Connecting; this.MaxConcurrentRequests = 1; this.MaxQueuedRequests = 100; this.fiber = new PoolFiber(); this.fiber.Start(); }
public LRClient() { ServerConnected = false; OnLogin = false; this.peer = new PhotonPeer(this, ConnectionProtocol.Udp); this.fiber = new PoolFiber(); this.fiber.Start(); }
/// <summary> /// Initializes a new instance of the <see cref="MmoRadar"/> class. /// </summary> public MmoRadar() { this.fiber = new PoolFiber(); this.fiber.Start(); this.channel = new MessageChannel<ItemEventMessage>(ItemEventMessage.CounterEventSend); this.itemPositions = new Dictionary<Item, float[]>(); this.itemSubscriptions = new Dictionary<Item, IDisposable>(); this.actionQueue = new ActionQueue(this, this.fiber); }
public PlaylistController(IFiber fiber, ISubscriber<RichYouTubeClip> newClips, ISubscriber<RichYouTubeClip> finishedPlaying, IPublisher<PlayerCommand> playerCommands) { this.playerCommands = playerCommands; this.newClipSubscription = newClips.Subscribe(fiber, NewClip); this.finishedSubscription = finishedPlaying.Subscribe(fiber, Finished); }
public IDisposable Schedule(IFiber fiber, Action action, TimeSpan dueTime) { if (dueTime.TotalMilliseconds <= 0) { var pending = new PendingAction(action); fiber.Enqueue(pending.Execute); return pending; } return new TimerAction(fiber, action, dueTime); }
public Client(string username) { this.username = username; this.fiber = new PoolFiber(); this.fiber.Start(); this.peerListener = new PeerListener(username, this.OnConnectCallback); this.peer = new PhotonPeer(this.peerListener, Settings.UseTcp ? ConnectionProtocol.Tcp : ConnectionProtocol.Udp); this.connectResetEvent = new AutoResetEvent(false); }
private void ExecuteOnTimerThread(IFiber fiber) { if (_interval.Ticks == TimeSpan.FromMilliseconds(-1).Ticks || _cancelled) { fiber.Remove(this); DisposeTimer(); } if (!_cancelled) fiber.Enqueue(Execute); }
public HttpRequestQueue(IFiber fiber) { this.QueueState = HttpRequestQueueState.Connecting; this.MaxConcurrentRequests = 1; this.MaxQueuedRequests = 100; this.ReconnectInterval = TimeSpan.FromMinutes(1); this.fiber = fiber; this.fiber.Start(); }
void MainPage_Loaded(object sender, RoutedEventArgs e) { if (fiber == null) { fiber = new DispatcherFiber(SynchronizationContext.Current); fiber.Start(); channels.TimeUpdate.SubscribeToLast(fiber, OnTimeUpdate, 0); new UpdateController(channels); } }
public MailReader(ServerAddress popServerAddress, long checkIntervalMs, bool deleteReadMessages, IFiber fiber, IPublisher<MailMessage> messageChannel) { this.popServerAddress = popServerAddress; this.messageChannel = messageChannel; this.deleteReadMessages = deleteReadMessages; this.imap = new ImapClient(popServerAddress.Host, popServerAddress.Username, popServerAddress.Password, ImapClient.AuthMethods.Login, popServerAddress.Port, popServerAddress.Ssl); imap.SelectMailbox("INBOX"); imap.NewMessage += HandleNewMessage; }
public static void ExecuteOnlyAfterStart(IFiber fiber) { using (fiber) using (var reset = new AutoResetEvent(false)) { fiber.Enqueue(() => reset.Set()); Assert.IsFalse(reset.WaitOne(1, false)); fiber.Start(); Assert.IsTrue(reset.WaitOne(1000, false)); } }
public static void TestPubSubSimple(IFiber fiber) { using (fiber) using (var reset = new AutoResetEvent(false)) { var channel = new Channel<string>(); channel.Subscribe(fiber, obj => reset.Set()); channel.Publish("hello"); Assert.IsTrue(reset.WaitOne(5000, false)); } }
public UnifiedMessagingController( IUnifiedMessagingService messagingService, MessageRepository messageRepository, IMessageFormatter formattingMessenger, IFiber fiber) { _MessagingService = messagingService; _MessageRepository = messageRepository; _FormattingMessenger = formattingMessenger; _Fiber = fiber; _MessagingService.MessagesReceived += _MessagingService_MessagesReceived; }
public PushPullSocketPortSpecs() { Context1 = NetMQContext.Create(); Context2 = NetMQContext.Create(); RcvdSignal = new ManualResetEvent(false); ClientFiber = PoolFiber.StartNew(); Pull = new PullSocket<string>(Context1, "tcp://localhost:6002", x => Encoding.Unicode.GetString(x), Channel); Push = new SendSocket<string>(Context2, "tcp://localhost:6002", s => Encoding.Unicode.GetBytes(s), ZmqSocketType.Push, false); }
public PubSubSpecs() { ClientFiber = PoolFiber.StartNew(); Context1 = NetMQContext.Create(); Send = new SendSocket<string>(Context1, "tcp://localhost:6001", s => Encoding.Unicode.GetBytes(s)); Context2 = NetMQContext.Create(); RcvdSignal = new ManualResetEvent(false); Subscriber = new SubscribeSocket<string>(Context2, "tcp://localhost:6001", x => Encoding.Unicode.GetString(x), Channel); Subscriber.SubscribeAll(); }
public static void TestBatchingWithKey(IFiber fiber) { using (fiber) using (var reset = new ManualResetEvent(false)) { var counter = new Channel<int>(); Action<IDictionary<String, int>> cb = batch => { if (batch.ContainsKey("9")) reset.Set(); }; Converter<int, String> keyResolver = x => x.ToString(); //disposed with fiber counter.SubscribeToKeyedBatch(fiber, keyResolver, cb, TimeSpan.FromMilliseconds(1)); for (int i = 0; i < 10; i++) counter.Publish(i); Assert.IsTrue(reset.WaitOne(10000, false)); } }
/// <summary> /// Initializes a new instance of the <see cref="Npc"/> class. /// </summary> /// <param name="position"> /// The position. /// </param> /// <param name="properties"> /// The properties. /// </param> /// <param name="itemId"> /// The item id. /// </param> /// <param name="itemType"> /// The item Type. /// </param> /// <param name="world"> /// The world. /// </param> /// <param name="viewDistanceEnter"> /// The view Distance Enter. /// </param> /// <param name="viewDistanceExit"> /// The view Distance Exit. /// </param> public Npc(Vector position, Hashtable properties, string itemId, byte itemType, IWorld world, Vector viewDistanceEnter, Vector viewDistanceExit) { this.fiber = new PoolFiber(); this.representation = new NpcItem(position, properties, itemId, itemType, world, this.fiber); if (!world.ItemCache.AddItem(this.representation)) { throw new InvalidOperationException(); } this.fiber.Start(); this.interestArea = new NpcInterestArea(itemId, world); this.interestArea.AttachToItem(this.representation); this.interestArea.ViewDistanceEnter = viewDistanceEnter; this.interestArea.ViewDistanceExit = viewDistanceExit; this.interestArea.UpdateInterestManagement(); this.representation.Position = position; this.representation.UpdateInterestManagement(); }