Ejemplo n.º 1
0
        public FrmTester()
        {
            InitializeComponent();
            log = new TextBoxStreamWriter(txtConsole);

            modules = new Dictionary<string, ConnectionManager>();
            autoResponders = new List<AutoResponder>();
            prompters = new List<Prompter>();
            dataReceived = new ProducerConsumer<ReceivedPacket>(100);
            receivedResponses = new List<Response>();
            quickCommands = new List<QuickCommand>();

            ValidateAddModuleButton();
            ValidateAddAutoResponderButton();
            ValidateAddPrompterButton();
            ValidateStartPerformanceTest();
            ValidateAddQuickCommandButton();
            SelectModule(null);
            SelectResponder(null);
            SelectPrompter(null);
            SelectQuickCommand(null);

            dlgConsole = new StringEventHandler(Console);
            dlgMainThreadTask = new ThreadStart(MainThreadTask);
            dlgGetPromptDialog = new GetPromptDialogCaller(GetPromptDialog);
            dlgShowPromptDialog = new ShowPromptDialogCaller(ShowPromptDialog);

            stopwatch = new Stopwatch();
            mainThread = new Thread(dlgMainThreadTask);
            mainThread.IsBackground = true;
            mainThread.Start();
        }
Ejemplo n.º 2
0
        public override void Fight(IDynamicObject other)
        {
            // a local Action for the winner and the loser
            void act(IDynamicObject winner, IDynamicObject loser)
            {
                // add 2 to the strength of the winner
                winner.AddStrength(2);
                // the loser is now depressed
                loser.SetState(State.Depressed);

                ProducerConsumer.Produce(String.Format("Object number {0} won agains object number {1}",
                                                       winner.Id, loser.Id));
            }

            /// the winner of the fight is the object with more strength. if the strengths of objects are the same
            /// than there is no winner
            if (Strength > other.Strength || other.DeBuff == DeBuff.Cocoon)
            {
                act(this, other);
            }
            else if (other.Strength > Strength)
            {
                act(other, this);
            }
        }
 public static async Task TestMethod()
 {
     // Here we separate all the Tasks in distinct threads
     CancellationTokenSource cancelSource = new CancellationTokenSource();
     Task c = Task.Run(async() =>
     {
         Console.WriteLine("Press any key to cancel from thread " + Thread.CurrentThread.ManagedThreadId.ToString());
         Console.ReadKey();     // if a key is pressed, we cancel
         cancelSource.Cancel();
     });
     Task sqs = Task.Run(async() =>
     {
         Console.WriteLine("Amazon on thread " + Thread.CurrentThread.ManagedThreadId.ToString());
         while (true)
         {
             ProducerConsumer.BackgroundFakedAmazon();     // We produce 50 Strings each second
             await Task.Delay(1000);
         }
     });
     Task deq = Task.Run(async() =>
     {
         Console.WriteLine("Dequeue on thread " + Thread.CurrentThread.ManagedThreadId.ToString());
         while (true)
         {
             ProducerConsumer.DequeueData();     // Dequeue 20 Strings each 100ms
             await Task.Delay(100);
         }
     });
     Task process = Task.Run(() =>
     {
         Console.WriteLine("Process on thread " + Thread.CurrentThread.ManagedThreadId.ToString());
         ProducerConsumer.BackgroundParallelConsumer();     // Process all the Strings in the BlockingCollection
     });
     await Task.WhenAll(c, sqs, deq, process);
 }
Ejemplo n.º 4
0
 public ChannelViewModel()
 {
     if (IsInDesignMode)
     {
         return;
     }
     //Subscribe to start stop events on main
     MainViewModel.Start += StartAcquisition;
     MainViewModel.Stop  += StopAcquisition;
     //Set up char collections
     _plotData_live = new ChartCollection <double>(2000);
     _plotData_seal = new ChartCollection <double, double>();
     //Create buffer with 1s worth of storage
     _liveDump                = new ProducerConsumer <double>(HardwareSettings.DAQ.Rate);
     _sealTestDump            = new ProducerConsumer <IndexedSample>(HardwareSettings.DAQ.Rate);
     _displayUpdater          = new DispatcherTimer();
     _displayUpdater.Tick    += TimerEvent;
     _displayUpdater.Interval = new TimeSpan(0, 0, 0, 0, 5);
     _displayUpdater.Start();
     RaisePropertyChanged(nameof(VC));
     if (ClampModeChanged != null)
     {
         ClampModeChanged.Invoke(new ClampModeChangedArgs(ChannelIndex, VC ? DAQ.ClampMode.VoltageClamp : DAQ.ClampMode.CurrentClamp));
     }
 }
Ejemplo n.º 5
0
        public FrmTester()
        {
            InitializeComponent();
            log = new TextBoxStreamWriter(txtConsole);

            modules           = new Dictionary <string, ConnectionManager>();
            autoResponders    = new List <AutoResponder>();
            prompters         = new List <Prompter>();
            dataReceived      = new ProducerConsumer <ReceivedPacket>(100);
            receivedResponses = new List <Response>();
            quickCommands     = new List <QuickCommand>();

            ValidateAddModuleButton();
            ValidateAddAutoResponderButton();
            ValidateAddPrompterButton();
            ValidateStartPerformanceTest();
            ValidateAddQuickCommandButton();
            SelectModule(null);
            SelectResponder(null);
            SelectPrompter(null);
            SelectQuickCommand(null);

            dlgConsole          = new StringEventHandler(Console);
            dlgMainThreadTask   = new ThreadStart(MainThreadTask);
            dlgGetPromptDialog  = new GetPromptDialogCaller(GetPromptDialog);
            dlgShowPromptDialog = new ShowPromptDialogCaller(ShowPromptDialog);

            stopwatch  = new Stopwatch();
            mainThread = new Thread(dlgMainThreadTask);
            mainThread.IsBackground = true;
            mainThread.Start();
        }
Ejemplo n.º 6
0
        private async Task <T> CreateListenerTask <T>(
            Func <CancellationToken, Task <T> > producer,
            Channel <T> channel,
            Func <T, CancellationToken, Task <bool> > consumer,
            CancellationToken cancellationToken)
        {
            using var cts       = new CancellationTokenSource();
            using var linkedCts = CancellationTokenSource.CreateLinkedTokenSource(cts.Token, cancellationToken);

            var producerToChannelTask = ProducerConsumer.CreateAsync(
                producer,
                async(i, c) =>
            {
                await channel.Writer.WriteAsync(i, c);
                return(true);
            },
                linkedCts.Token,
                true);
            var channelToConsumerTask = ProducerConsumer.CreateAsync(
                (c) => channel.Reader.ReadAsync(c).AsTask(),
                consumer,
                linkedCts.Token,
                true);

            await Task.WhenAny(producerToChannelTask, channelToConsumerTask);

            // Cancel and awaits the both tasks again
            cts.Cancel();

            var items = await Task.WhenAll(producerToChannelTask, channelToConsumerTask);

            return(items.FirstOrDefault(i => i != null));
        }
Ejemplo n.º 7
0
        public async Task StartAsync(CancellationToken cancellationToken = default(CancellationToken))
        {
            await ListenerSemaphore.WaitAsync(cancellationToken);

            await _transportListener.StartAsync();

#pragma warning disable 4014
            ProducerConsumer.CreateAsync(

                c => _transportListener.AcceptTransportAsync(c),
                async t =>
            {
                await t.OpenAsync(null, _cts.Token);

                var serverChannel = new ServerChannel(
                    Guid.NewGuid().ToString(),
                    new Node("postmaster", "msging.net", "instance"),
                    t,
                    TimeSpan.FromSeconds(60),
                    autoReplyPings: true);

                var clientNode = new Node("client", "msging.net", "instance");

                await serverChannel.EstablishSessionAsync(
                    new[] { SessionCompression.None },
                    new[] { SessionEncryption.None },
                    new[]
                {
                    AuthenticationScheme.Guest,
                    AuthenticationScheme.Key,
                    AuthenticationScheme.Plain,
                    AuthenticationScheme.Transport,
                },
                    (n, a) => new AuthenticationResult(null, clientNode).AsCompletedTask(), _cts.Token);

                var channelListener = new ChannelListener(
                    m => TaskUtil.TrueCompletedTask,
                    n => TaskUtil.TrueCompletedTask,
                    async c =>
                {
                    if (c.Status == CommandStatus.Pending)
                    {
                        await serverChannel.SendCommandAsync(
                            new Command(c.Id)
                        {
                            Status = CommandStatus.Success,
                            Method = c.Method
                        },
                            _cts.Token);
                    }
                    return(true);
                });

                channelListener.Start(serverChannel);

                return(true);
            },
                _cts.Token);
        }
Ejemplo n.º 8
0
 static IFileWriter SetupFileWriter(IBlockCompressorUowOutputFactory outputFactory,
                                    ProducerConsumer <IByteChunk> finishChain)
 {
     return(new FileWriter(new ThreadingImpl(),
                           new FileWriterUow(new IoImpl(),
                                             outputFactory.GetAllOutputs(),
                                             finishChain)));
 }
Ejemplo n.º 9
0
 /// <summary>
 /// Initializes a new instance of AudioPlayer
 /// </summary>
 public AudioPlayer64()
 {
     syncObj = new Object();
     playQueue = new ProducerConsumer<PlayAudioTask>();
     playThread = new Thread(new ThreadStart(PlayAudioThreadTask));
     playThread.IsBackground = true;
     playThread.Start();
 }
 /// <summary>
 /// Initializes a new instance of the ModuleClientPlugin class
 /// </summary>
 /// <param name="plugin">The plugin application module</param>
 internal ModuleClientPlugin(IModulePlugin plugin)
     : base(plugin.ModuleName)
 {
     if (plugin == null)
         throw new ArgumentNullException();
     this.plugin = plugin;
     dataReceived = new ProducerConsumer<string>(100);
 }
Ejemplo n.º 11
0
 /// <summary>
 /// Initializes a new instance of AudioPlayer
 /// </summary>
 public AudioPlayer32()
 {
     syncObj    = new Object();
     playQueue  = new ProducerConsumer <PlayAudioTask>();
     playThread = new Thread(new ThreadStart(PlayAudioThreadTask));
     playThread.IsBackground = true;
     playThread.Start();
 }
 public ModelPredictorService(ModelsService modelsService, IDataDirectoryService dataDirectoryService)
 {
     _modelsService        = modelsService;
     _dataDirectoryService = dataDirectoryService;
     _producerConsumer     = new ProducerConsumer <Action>(1, ConsumeAction);
     //_producerConsumer.Add(() => _y = Py.GIL());
     //_producerConsumer.Start();
 }
Ejemplo n.º 13
0
 private Task <T> CreateListenerTask <T>(Func <CancellationToken, Task <T> > producer, Func <T, CancellationToken, Task <bool> > consumer)
 {
     return(ProducerConsumer.CreateAsync(
                producer,
                consumer,
                _cts.Token,
                true));
 }
        public IProducerConsumer <IByteChunk> CreateOutput()
        {
            var result = new ProducerConsumer <IByteChunk>(_outputCapacity,
                                                           new ProducerConsumerOrderedQueue <IByteChunk>());

            _data.Add(result);
            return(result);
        }
Ejemplo n.º 15
0
 public ImageSourceManager()
 {
     this.selectedSourceIndex = -1;
     this.capturedImages = new ProducerConsumer<Bitmap>(30);
     this.sources = new ImageSourceCollection(this);
     this.sources.ElementAdded += new ImageSourceCollectionChanged(sources_ElementAdded);
     this.sources.ElementRemoved += new ImageSourceCollectionChanged(sources_ElementRemoved);
     this.dlgImageProduced = new ImageProducedEventHandler(element_ImageProduced);
 }
Ejemplo n.º 16
0
 /// <summary>
 /// Initializes a new instance of SpeechGenerator
 /// </summary>
 public SpeechGenerator()
 {
     this.voiceNames                = new SortedList <string, int>(20, StringComparer.OrdinalIgnoreCase);
     this.pronunciation             = new PronunciationRuleList(200);
     this.speechQueue               = new ProducerConsumer <SpeechTextTask>(100);
     this.speechThread              = new Thread(new ThreadStart(SpeechThreadTask));
     this.speechThread.IsBackground = true;
     this.speechThread.Start();
 }
Ejemplo n.º 17
0
        public void ProducerConsumer()
        {
            ProducerConsumer pc = new ProducerConsumer();

            while (!pc.IsDoneReading || !pc.IsDoneWriting)
            {
                Thread.Sleep(1000);
            }
            int a = 0;
        }
Ejemplo n.º 18
0
 /// <summary>
 /// Initializes a new instance of the ModuleClientPlugin class
 /// </summary>
 /// <param name="plugin">The plugin application module</param>
 internal ModuleClientPlugin(IModulePlugin plugin)
     : base(plugin.ModuleName)
 {
     if (plugin == null)
     {
         throw new ArgumentNullException();
     }
     this.plugin  = plugin;
     dataReceived = new ProducerConsumer <string>(100);
 }
Ejemplo n.º 19
0
        public void EnqueueTest_AddNull()
        {
            //arrange
            var producer = new ProducerConsumer <Block>();

            //act

            //assert
            Assert.ThrowsException <ArgumentNullException>(() => producer.Enqueue(null));
        }
Ejemplo n.º 20
0
 // TODO consider adding unity to the project
 static IFileReader SetupUncompressedFileReader(
     ProducerConsumer <IByteChunk> readerToProcessorsChain,
     ProducerConsumer <IByteChunk> finishChain)
 {
     return(new FileReader(
                new ThreadingImpl(),
                new FileReaderUow(UncompressedReadBlockSize,
                                  new IoImpl(),
                                  readerToProcessorsChain,
                                  finishChain)));
 }
Ejemplo n.º 21
0
 public override void ActOnStaticObject(Food obj)
 {
     ProducerConsumer.Produce(String.Format("Spider number {0} ate food!", Id));
     Strength++;
     agilityProgress++;
     if (agilityProgress == 2)
     {
         agilityProgress = 0;
         Agility++;
     }
 }
Ejemplo n.º 22
0
        static IBlockCompressor SetupBlockCompressor(
            ProducerConsumer <IByteChunk> readerToProcessorsChain,
            IBlockCompressorUowOutputFactory outputFactory)
        {
            var blockCompressorUowFactory = new BlockCompressorUowFactory(readerToProcessorsChain,
                                                                          outputFactory,
                                                                          new GzipStream());
            var starter = new BlockCompressorStarter(new ThreadingImpl(),
                                                     blockCompressorUowFactory);

            return(new BlockCompressor(CompressThreadsCount, starter));
        }
Ejemplo n.º 23
0
        public void DequeueTest_DequeueItemFromStoppedQueueIsNull()
        {
            //arrange
            var producer = new ProducerConsumer <Block>();

            //act
            producer.Stop();
            var resultItemFromDequeue = producer.Dequeue();

            //assert
            Assert.IsNull(resultItemFromDequeue);
        }
Ejemplo n.º 24
0
        public void EnqueueTest_WhenQueueStopped()
        {
            //arrange
            var producer = new ProducerConsumer <Block>();
            var block    = new Block(0, null);

            //act
            producer.Stop();

            //assert
            Assert.ThrowsException <InvalidOperationException>(() => producer.Enqueue(block));
        }
Ejemplo n.º 25
0
        /// <summary>
        /// Initializes a new instance of the ModuleBlackboard class
        /// </summary>
        /// <param name="name">Module name</param>
        public ModuleBlackboard(string name) : base(name)
        {
            sharedVariables = new SharedVariableCollection();
            sharedVariables.Add(svAliveModules     = new AliveModulesSharedVariable(this));
            sharedVariables.Add(svBusyModules      = new BusyModulesSharedVariable(this));
            sharedVariables.Add(svConnectedModules = new ConnectedModulesSharedVariable(this));
            sharedVariables.Add(svModules          = new ModulesSharedVariable(this));
            sharedVariables.Add(svReadyModules     = new ReadyModulesSharedVariable(this));
            sharedVariables.Add(svVariableList     = new VariableListSharedVariable(this));

            pendingSubscriptions = new Dictionary <string, List <SharedVariableSubscription> >();
            // Add default blackboard commands
            //this.Prototypes.Add(pttAlive);
            //this.Prototypes.Add(pttBin);
            //this.Prototypes.Add(pttBusy);
            //this.Prototypes.Add(pttConnected);
            //this.Prototypes.Add(pttReady);
            this.Prototypes.Add(new Prototype("alive", true, true, 300, true));
            this.Prototypes.Add(new Prototype("bin", true, true, 300, true));
            this.Prototypes.Add(new Prototype("busy", true, true, 300, true));
            this.Prototypes.Add(new Prototype("connected", true, true, 300, true));
            this.Prototypes.Add(new Prototype("ready", true, true, 300, true));
            this.Prototypes.Add(new Prototype("modules", false, true, 300, true));
            this.Prototypes.Add(new Prototype("idletime", true, true, 300, true));
            this.Prototypes.Add(new Prototype("setupmodule", true, true, 500, true));
            this.Prototypes.Add(new Prototype("querymodule", true, true, 300, true));
            this.Prototypes.Add(new Prototype("reset", true, false, 300, true));
            this.Prototypes.Add(new Prototype("restart_test", true, false, 300, true));
            this.Prototypes.Add(new Prototype("bbstatus", true, true, 300, true));
            this.Prototypes.Add(new Prototype("mstatus", true, true, 300, true));
            this.Prototypes.Add(new Prototype("mystat", true, false, 300, true));

            // Remote module start and stop commands
            this.Prototypes.Add(new Prototype("start_module_app", true, true, 3000, true));
            this.Prototypes.Add(new Prototype("stop_module_app", true, false, 3000, true));

            // Shared Variable related
            this.Prototypes.Add(new Prototype("suscribe_var", true, true, 500, true));
            this.Prototypes.Add(new Prototype("subscribe_var", true, true, 500, true));
            this.Prototypes.Add(new Prototype("unsubscribe_var", true, true, 500, true));

            // Moved to parent class
            //this.Prototypes.Add(new Prototype("create_var", true, true, 300, true));
            //this.Prototypes.Add(new Prototype("list_vars", true, true, 300, true));
            //this.Prototypes.Add(new Prototype("read_var", true, true, 300, true));
            //this.Prototypes.Add(new Prototype("read_vars", true, true, 300, true));
            //this.Prototypes.Add(new Prototype("write_var", true, true, 300, true));

            commandsReceived = new ProducerConsumer <ITextCommand>(50);
            processManager   = new ProcessManager();
            msc = new MachineStatusCollection(this);
        }
Ejemplo n.º 26
0
		public void TestProducerConsumer()
		{
			var ProducerConsumer = new ProducerConsumer<byte>();
			Assert.AreEqual(0, ProducerConsumer.AvailableForRead);
			ProducerConsumer.Write(Encoding.UTF8.GetBytes("Hello World!"));
			Assert.AreEqual(12, ProducerConsumer.AvailableForRead);
			ProducerConsumer.Skip(0);
			Assert.AreEqual(12, ProducerConsumer.AvailableForRead);
			ProducerConsumer.Skip(6);
			Assert.AreEqual(6, ProducerConsumer.AvailableForRead);
			Assert.AreEqual("World!", Encoding.UTF8.GetString(ProducerConsumer.PeekGet(6)));
			Assert.AreEqual(6, ProducerConsumer.AvailableForRead);
		}
Ejemplo n.º 27
0
        private async void PhoneProducer_Added(ProducerWatcher sender, AllJoynServiceInfo args)
        {
            Debug.WriteLine("Attempt to join session for phone...");

            var phoneJoin = await ProducerConsumer.JoinSessionAsync(args, sender);

            if (phoneJoin.Status == AllJoynStatus.Ok)
            {
                _phoneMessage = phoneJoin.Consumer;
                Debug.WriteLine("Consumer has been successfully initialized");
                // await _phoneMessage.Signals
            }
        }
    static void Main()
    {
        queue = new ProducerConsumer();
        new Thread(new ThreadStart(ConsumerJob)).Start();

        Random rng = new Random(0);
        for (int i = 0; i < 10; i++)
        {
            Console.WriteLine("Producing {0}", i);
            queue.Produce(i);
            Thread.Sleep(rng.Next(1000));
        }
    }
Ejemplo n.º 29
0
 public GrpcProtoFactory(GrpcPluginFactory pluginFactory, IOptions <GrpcHttpGatewayConfiguration> config, CodeGenerater codeGenerater, CodeBuilder codeBuilder, ILogger <GrpcProtoFactory> logger)
 {
     this.logger        = logger;
     this.pluginFactory = pluginFactory;
     this.codeGenerater = codeGenerater;
     this.codeBuilder   = codeBuilder;
     this.config        = config.Value;
     protoQueue         = new ProducerConsumer <string>(protoFileName => LoadAsync(protoFileName).Wait());
     if (this.config.ProtoMonitor)
     {
         MonitorStart();
     }
 }
Ejemplo n.º 30
0
        public void DequeueTest_DequeueItemFromNotEmptyQueue()
        {
            //arrange
            var producer = new ProducerConsumer <Block>();
            var block    = new Block(0, null);

            //act
            producer.Enqueue(block);
            var resultItemFromDequeue = producer.Dequeue();

            //assert
            Assert.IsNotNull(resultItemFromDequeue);
        }
    static void Main()
    {
        queue = new ProducerConsumer();
        new Thread(new ThreadStart(ConsumerJob)).Start();

        Random rng = new Random(0);

        for (int i = 0; i < 10; i++)
        {
            Console.WriteLine("Producing {0}", i);
            queue.Produce(i);
            Thread.Sleep(rng.Next(1000));
        }
    }
Ejemplo n.º 32
0
        private async void PhoneProducer_Added(ProducerWatcher sender, AllJoynServiceInfo args)
        {
            Debug.WriteLine("Attempt to join session for phone...");

            var phoneJoin = await ProducerConsumer.JoinSessionAsync(args, sender);

            if (phoneJoin.Status == AllJoynStatus.Ok)
            {
                _phoneMessage = phoneJoin.Consumer;
                Debug.WriteLine("Consumer has been successfully initialized");
               // await _phoneMessage.Signals

            }
        }
Ejemplo n.º 33
0
        public void EnqueueTest_SuccessfullyAdding()
        {
            //arrange
            var producer = new ProducerConsumer <Block>();
            var block    = new Block(0, null);

            //act
            producer.Enqueue(block);
            producer.Enqueue(block);
            var resultIsEmpty = producer.IsEmpty;

            //assert
            Assert.AreEqual(resultIsEmpty, false);
        }
Ejemplo n.º 34
0
        private void produceConsume(object sender, RoutedEventArgs e)
        {
            ProducerConsumer pc = new ProducerConsumer(this);

            ProducerConsumer.SharedBuffer = 20;
            ProducerConsumer.mut          = new Mutex(false, "Tr");
            ProducerConsumer.threadVec    = new Thread[2];
            ProducerConsumer.threadVec[0] = new Thread(new ThreadStart(pc.Consumer));
            ProducerConsumer.threadVec[1] = new Thread(new ThreadStart(pc.Producer));
            ProducerConsumer.threadVec[0].Start();
            ProducerConsumer.threadVec[1].Start();
            ProducerConsumer.threadVec[0].Join();
            ProducerConsumer.threadVec[1].Join();
        }
Ejemplo n.º 35
0
 private async Task <T> CreateListenerTask <T>(Func <CancellationToken, Task <T> > producer, Func <T, Task <bool> > consumer)
 {
     try
     {
         return(await ProducerConsumer.CreateAsync(
                    producer,
                    consumer,
                    _cts.Token).ConfigureAwait(false));
     }
     catch (OperationCanceledException) when(_cts.IsCancellationRequested)
     {
         return(default(T));
     }
 }
Ejemplo n.º 36
0
        static void Main()
        {
            ProducerConsumer<ActionWrapper> pc = new ProducerConsumer<ActionWrapper>(1, 10000, 1000, 5, 1, 5000);
            pc.OnConsume += OnConsume;

            for (int i = 0; i < 100; i++)
            { 
                ActionWrapper wrapper = new ActionWrapper();
                wrapper.Parameter = i.ToString();
                wrapper.DoAction = GetAction();
                pc.Produce(wrapper);
            }

            Console.ReadLine();
        }
Ejemplo n.º 37
0
        static void Main(string[] args)
        {
            // TODO
            // complete ProducerConsumer
            ProducerConsumer pc = new ProducerConsumer();

            pc.Run();


            // TODO
            // RunFaceDetectionsPipeline();

            Console.WriteLine("Completed");
            Console.ReadLine();
        }
Ejemplo n.º 38
0
 private void FightDifferentObject(IDynamicObject other)
 {
     if (other.DeBuff == DeBuff.Cocoon)
     {
         agilityProgress = 0;
         Strength++;
         other.SetState(State.Dead);
         ProducerConsumer.Produce(String.Format("Spider number {0} ate another object with id {1}", Id, other.Id));
     }
     else
     {
         other.DeBuff = DeBuff.Cocoon;
         ProducerConsumer.Produce(String.Format("object number {0} became a cocoon", other.Id));
     }
 }
Ejemplo n.º 39
0
        /// <summary>
        /// Initializes a new instance of the TextBoxStreamWriter class
        /// </summary>
        /// <param name="logFile">The path of the file to which dump the contents to</param>
        public ConsoleLogWriter(string logFile)
        {
            this.pending = new ProducerConsumer<StringToken>(100);
            this.waitingHadle = new StringBuilder(1024);
            this.OpenLogFileStream(logFile, out this.logFile);

            this.appendDate = false;
            this.consoleVerbosityThreshold = 5;
            this.defaultPriority = 5;
            this.disposed = false;
            this.disposing = false;
            this.recordId = 0;
            this.logRecordTagOpen = false;
            this.logTagOpen = false;
            SetupThread();
        }
            public void Execute()
            {
                queue = new ProducerConsumer();
                Thread consumer=new Thread(new ThreadStart(ConsumerJob));
                consumer.Start();

                Random rng = new Random(0);
                for (int i = 0; i < 10; i++)
                {
                    Console.WriteLine("Producing {0}", i);
                    queue.Produce(i);
                    Thread.Sleep(rng.Next(100));
                }

                Console.WriteLine("Waiting for consumer to finish....");
                consumer.Join();
                Console.WriteLine("Consumer finished his job....");
            }
Ejemplo n.º 41
0
		/// <summary>
		/// initializes a new instance of FrmAppLauncher
		/// </summary>
		public FrmAppLauncher()
		{
			InitializeComponent();
			icon.Icon = Properties.Resources.icoOrange;
			icon.BalloonTipText = @"Use following:

* action=""check"" processName=""Name of process to kill"" programPath=""Path of program to run"" [programArgs=""Program arguments""]

* action=""kill"" processName=""Name of process to kill""

* action=""run"" programPath=""Path of program to run"" [programArgs=""Program arguments""]
";
			oPause = new object();
			cnnMan = new ConnectionManager("AppLauncherSvc", 2300);
			cnnMan.Started += new ConnectionManagerStatusChangedEventHandler(cnnMan_Started);
			cnnMan.StatusChanged += new ConnectionManagerStatusChangedEventHandler(cnnMan_StatusChanged);
			cnnMan.Stopped += new ConnectionManagerStatusChangedEventHandler(cnnMan_Stopped);
			cnnMan.DataReceived += new ConnectionManagerDataReceivedEH(cnnMan_DataReceived);
			dataReceived = new ProducerConsumer<TcpPacket>(10);
			dlgExecute = new ParameterizedThreadStart(Execute);
			rxAction = new Regex(@"action\s*=\s*\""(?<action>[A-Za-z]+)\""", RegexOptions.Compiled);
		}
        public void Notify(List<IConsumerMessage> msgs, ConsumerContext context, ProducerConsumer<Action> executorService, IPipeline<object> pipeline)
        {
            foreach (IConsumerMessage msg in msgs)
            {
                NackDelayedBrokerConsumerMessage nackDelayedMsg = new NackDelayedBrokerConsumerMessage((BrokerConsumerMessage)msg);
                List<IConsumerMessage> singleMsg = new List<IConsumerMessage>();
                singleMsg.Add(nackDelayedMsg);

                int retries = 0;
                while (true)
                {
                    pipeline.Put(new Pair<ConsumerContext, List<IConsumerMessage>>(context, singleMsg));

                    if (nackDelayedMsg.BaseConsumerMessage.Status == MessageStatus.FAIL)
                    {
                        // reset status to enable reconsume or nack
                        nackDelayedMsg.BaseConsumerMessage.ResetStatus();
                        if (retries < m_retryPolicy.GetRetryTimes())
                        {
                            Sleep(m_retryPolicy.NextScheduleTimeMillis(retries, 0));
                            retries++;
                        }
                        else
                        {
                            msg.Nack();
                            break;
                        }
                    }
                    else
                    {
                        msg.Ack();
                        break;
                    }
                }
            }
        }
 public void Notify(List<IConsumerMessage> msgs, ConsumerContext context, ProducerConsumer<Action> executorService, IPipeline<object> pipeline)
 {
     pipeline.Put(new Pair<ConsumerContext, List<IConsumerMessage>>(context, msgs));
 }
Ejemplo n.º 44
0
        public BaseConsumerTask(ConsumerContext context, int partitionId, int localCacheSize)
        {
            Context = context;
            PartitionId = partitionId;
            msgs = new BlockingQueue<IConsumerMessage>(localCacheSize);

            LeaseManager = ComponentLocator.Lookup<ILeaseManager<ConsumerLeaseKey>>(BuildConstants.CONSUMER);
            ConsumerNotifier = ComponentLocator.Lookup<IConsumerNotifier>();
            EndpointClient = ComponentLocator.Lookup<IEndpointClient>();
            EndpointManager = ComponentLocator.Lookup<IEndpointManager>();
            MessageCodec = ComponentLocator.Lookup<IMessageCodec>();
            SystemClockService = ComponentLocator.Lookup<ISystemClockService>();
            Config = ComponentLocator.Lookup<ConsumerConfig>();
            retryPolicy = ComponentLocator.Lookup<IMetaService>().FindRetryPolicyByTopicAndGroup(
                context.Topic.Name, context.GroupId);
            PullMessageResultMonitor = ComponentLocator.Lookup<IPullMessageResultMonitor>();

            pullMessageTaskExecutor = new ProducerConsumer<BasePullMessagesTask>(int.MaxValue);
            pullMessageTaskExecutor.OnConsume += RunPullMessageTask;

            renewLeaseTaskExecutor = new TimeoutNotifyProducerConsumer<RenewLeaseTask>(int.MaxValue);
            renewLeaseTaskExecutor.OnConsume += RunRenewLeaseTask;
        }
Ejemplo n.º 45
0
        /// <summary>
        /// Initializes a new instance of Blackboard
        /// </summary>
        private Blackboard()
        {
            this.modules = new ModuleCollection(this, 20);
            this.prototypes = new Dictionary<string, IPrototype>(1000);
            this.prototypesLock = new ReaderWriterLock();
            //modules.ModuleAdded += new ModuleClientAddRemoveEH(modules_ModuleAdded);
            //modules.ModuleRemoved += new ModuleClientAddRemoveEH(modules_ModuleRemoved);
            this.modules.ModuleAdded += new IModuleAddRemoveEH(modules_ModuleAdded);
            this.modules.ModuleRemoved += new IModuleAddRemoveEH(modules_ModuleRemoved);
            this.commandsPending = new ProducerConsumer<Command>(1000);
            this.commandsWaiting = new List<Command>(100);
            this.responses = new List<Response>(100);
            this.log = new LogWriter();
            this.log.VerbosityTreshold = verbosity;
            this.dataReceived = new ProducerConsumer<TcpPacket>(1000);
            this.retryQueue = new Queue<Response>(100);
            this.sendAttempts = 0;
            this.testTimeOut = TimeSpan.MinValue;
            this.autoStopTime = TimeSpan.MinValue;
            this.startupSequence = new StartupSequenceManager(this);
            this.shutdownSequence = new ShutdownSequenceManager(this);
            this.pluginManager = new BlackboardPluginManager(this);

            this.mainThreadRunningEvent = new ManualResetEvent(false);
            this.parserThreadRunningEvent = new ManualResetEvent(false);
        }
Ejemplo n.º 46
0
 static void Main()
 {
     var manager = new ProducerConsumer();
     manager.Start();
 }
Ejemplo n.º 47
0
 /// <summary>
 /// Initializes a new instance of SpeechGenerator
 /// </summary>
 public SpeechGenerator()
 {
     this.voiceNames = new SortedList<string, int>(20, StringComparer.OrdinalIgnoreCase);
     this.pronunciation = new PronunciationRuleList(200);
     this.speechQueue = new ProducerConsumer<SpeechTextTask>(100);
     this.speechThread = new Thread(new ThreadStart(SpeechThreadTask));
     this.speechThread.IsBackground = true;
     this.speechThread.Start();
 }
Ejemplo n.º 48
0
Archivo: Form1.cs Proyecto: lzhaofu/OSS
        private void btn_Start_Click(object sender, EventArgs e)
        {
            if (!_noticeFlag)
            {
                _noticeFlag = true;
                _noticeDateTime = DateTime.Now;
                Logging("启动[OSS更新]服务");
                SetbtnState(btn_Start, "停止[OSS更新]服务", true);
                SetlblState(lbl_text, "[OSS更新]扫描服务运行中(" + _noticeDateTime + ")", Color.Green);

                //重置提醒扫描状态:正在扫描--> 等到扫描
                var resetStandbyTask = new Task<bool>(() =>
                {
                    var isReset = false;
                    try
                    {
                        isReset = ResetAllRemindScan();
                    }
                    catch
                    {
                    }
                    return isReset;
                });
                resetStandbyTask.Start();
                resetStandbyTask.Wait();
                var isSuccess = resetStandbyTask.Result;
                if (isSuccess)
                {
                    Logging("重置\"扫描中\"的[OSS更新]扫描服务为等待扫描成功!");
                }
                else
                {
                    Logging("[OSS更新]扫描服务启动失败:重置\"扫描中\"的[OSS更新]扫描服务为等待扫描失败!");
                    _noticeFlag = false;
                    SetbtnState(btn_Start, "启动[OSS更新]扫描服务", true);
                    SetlblState(lbl_text, "[OSS更新]扫描服务停止", Color.Red);
                    return;
                }

                //初始化相关变量、工作线程
                //等到重置“发送中”任务结束后,才能执行下面任务:
                //获取[未提醒]列表数据,为[发起提醒]生产者提供生产方法
                var getRetryTimes = 0;
                Func<List<string>> ProduceFunc = () =>
                {
                    //休眠获取[提醒]列表数据,主要为了间断查询。
                    Thread.Sleep(_sleepQuery);
                    var unList = new List<string>();
                    try
                    {
                        unList = GetTaskList();
                        if (unList.Count > 0)
                        {
                            Logging("获取[OSS更新]队列成功!");
                        }
                        getRetryTimes = 0;
                    }
                    catch (Exception ex)
                    {
                        getRetryTimes = getRetryTimes + 1;
                        if (getRetryTimes >= _getQueryRetryTimes)
                        {
                            _noticeFlag = false;
                            Logging("[OSS更新]服务意外停止:获取[未更新]队列连续失败" + getRetryTimes + "次!|| 错误原因:" +(ex.InnerException == null ? ex.Message : ex.InnerException.ToString()),(string.IsNullOrWhiteSpace(ex.StackTrace) ? "" : ex.StackTrace));
                            ChangeAllServerState();
                            if (_producerConsumer != null)
                            {
                                _producerConsumer.Stop();
                            }
                        }
                        else
                        {
                            Logging("获取[未更新]队列连续失败" + getRetryTimes + "次!|| 错误原因:" +(ex.InnerException == null ? ex.Message : ex.InnerException.ToString()),(string.IsNullOrWhiteSpace(ex.StackTrace) ? "" : ex.StackTrace));
                        }
                    }
                    return unList;
                };

                int consumeRetryTimes = 0;
                //为[未提醒]消费者提供消费方法
                Action<string> notNoticeAction = item =>
                {
                    if (!string.IsNullOrEmpty(item))
                    {
                        long durTime = -1;
                        var durTimeUnit = "毫秒";
                        var durTimer = new Stopwatch();
                        durTimer.Start();
                        try
                        {
                            //执行活动提交服务
                            var result = PostRemind(item);
                            durTimer.Stop();
                            durTime = durTimer.ElapsedMilliseconds;
                            if (durTime >= 1000)
                            {
                                durTimeUnit = "秒";
                                durTime = durTime / 1000;
                            }
                            lock (_noticeLock)
                            {
                                consumeRetryTimes = 0;
                            }
                            Logging("[未更新]提交成功." + "(数据ID:" + item + ",运行结果:" + (result ? "提醒成功" : "提醒失败") + ",耗时:" +durTime.ToString() + durTimeUnit + ")");
                        }
                        catch (Exception ex)
                        {
                            lock (_noticeLock)
                            {
                                consumeRetryTimes++;
                                if (consumeRetryTimes >= _getQueryRetryTimes)
                                {
                                    _noticeFlag = false;
                                    Logging("[未更新]服务意外停止:提交提醒服务连续失败" + consumeRetryTimes + "次![其中包含ID:" + item +"]  || 错误原因:" +(ex.InnerException == null ? ex.Message : ex.InnerException.ToString()),(string.IsNullOrWhiteSpace(ex.StackTrace) ? "" : ex.StackTrace));
                                    ChangeAllServerState();
                                    if (_producerConsumer != null)
                                    {
                                        _producerConsumer.Stop();
                                    }
                                }
                                else
                                {
                                    Logging("[未更新]提交提醒服务连续失败" + consumeRetryTimes + "次![其中包含商家ID:" + item +"] || 错误原因:" +(ex.InnerException == null ? ex.Message : ex.InnerException.ToString()),(string.IsNullOrWhiteSpace(ex.StackTrace) ? "" : ex.StackTrace));
                                }
                            }
                        }
                        Thread.Sleep(_sleepPost);
                    }
                };
                //构造生产消费模式,初始化如生产方法,消费方法,指定消费者数量
                _producerConsumer = new ProducerConsumer<string>(ProduceFunc,notNoticeAction, _remainStandbyCount,_reminTaskNum);
                _producerConsumer.Start();
            }
            else //停止
            {
                _noticeFlag = false;
                if (_producerConsumer != null)
                {
                    _producerConsumer.Stop();
                }
                Logging("手动停止[未更新]扫描服务");

                SetbtnState(btn_Start, "启动[OSS更新]扫描服务", true);
                SetlblState(lbl_text, "[OSS更新]扫描服务停止", Color.Red);
            }
        }