Inheritance: WaitHandle
Beispiel #1
0
        public static CoalescedAnnounceResponse CoalescedAnnounce(this Tracker tracker, params IAnnounceRequest[] announceList)
        {
            InternalAnnounceResponseCollection annnounceResponses = new InternalAnnounceResponseCollection();
            Semaphore requestSemaphore = new Semaphore(TrackerSettings.MaxConcurrency, TrackerSettings.MaxConcurrency);
            IAsyncResult[] results = new IAsyncResult[announceList.Length];

            for(int i = 0; i < announceList.Length; i++)
                results[i] = tracker.BeginAnnounce(announceList[i], new AsyncCallback((result) => requestSemaphore.Release()), announceList[i].InfoHash);

            foreach (IAsyncResult result in results)
            {
                IAnnounceResponse response = null;

                try
                {
                    response = tracker.EndAnnounce(result);
                }
                catch { }

                if(response != null)
                    annnounceResponses.Add((InfoHash)result.AsyncState, new InternalAnnounceResponse(
                        response.Interval,
                        response.Complete,
                        response.Incomplete,
                        response.Peers)
                        );
            }

            return new CoalescedAnnounceResponse(annnounceResponses);
        }
Beispiel #2
0
 public _Semaphore(int value, string name)
 {
     this.count    = value;
     this.name     = name;
     threads       = new Queue();
     realSemaphore = new System.Threading.Semaphore(value, value);
 }
Beispiel #3
0
 public BootStrap()
 {
     Logger.Debug ("BootStrapping, This should be Fun");
     waitBootStrap = new Semaphore(0,1);
     state = new BootStrappingState();
     fileSystem = new InMemoryFileSystem (true);
 }
Beispiel #4
0
 public void Dispose()
 {
     if (semaphore != null) {
     semaphore.Dispose();
     semaphore = null;
       }
 }
        public DisplayHandler(iMonWrapperApi imon)
        {
            if (imon == null)
            {
                throw new ArgumentNullException("imon");
            }

            this.imon = imon;
            this.imon.StateChanged += stateChanged;
            this.queue = new List<Text>();

            this.icons = new Dictionary<iMonLcdIcons, bool>(Enum.GetValues(typeof(iMonLcdIcons)).Length);
            foreach (iMonLcdIcons icon in Enum.GetValues(typeof(iMonLcdIcons)))
            {
                this.icons.Add(icon, false);
            }

            this.discRotation = new System.Timers.Timer();
            this.discRotation.AutoReset = true;
            this.discRotation.Interval = 300;
            this.discRotation.Elapsed += discRotationElapsed;

            this.WorkerReportsProgress = false;
            this.WorkerSupportsCancellation = true;

            this.semReady = new Semaphore(0, 1);
            this.semWork = new Semaphore(0, 1);
        }
Beispiel #6
0
        public LocalPool(
            int numCommandThread = 4,
            int numMatLabThread = 4,
            int numCADThread = 2)
        {
            ts = new CancellationTokenSource();
            ct = ts.Token;

            tf = new TaskFactory(
                ct,
                TaskCreationOptions.LongRunning,
                TaskContinuationOptions.None,
                null);

            int numAllThread = numCommandThread + numMatLabThread + numCADThread;

            // do not use more threads than cores
            numAllThread = numAllThread < Environment.ProcessorCount ?
                numAllThread :
                Environment.ProcessorCount;

            NumAllThread = numAllThread;
            NumCommandThread = numCommandThread;
            NumMatLabThread = numMatLabThread;
            NumCADThread = numCADThread;

            SemAll = new Semaphore(numAllThread, numAllThread);
            SemJob = new Dictionary<Job.TypeEnum, Semaphore>();
            SemJob.Add(Job.TypeEnum.Command, new Semaphore(numCommandThread, numCommandThread));
            SemJob.Add(Job.TypeEnum.Matlab, new Semaphore(numMatLabThread, numMatLabThread));
            SemJob.Add(Job.TypeEnum.CAD, new Semaphore(numCADThread, numCADThread));
        }
Beispiel #7
0
        private void FriendsListForm_FormClosed(object sender, FormClosedEventArgs e)
        {
            if (_exitType == MainFormExitType.Exit)
            {
                if (_nrtcInit)
                {
                    //退出前需要结束音视频设备,防止错误的数据上报
                    MultimediaHandler.EndDevices();
                    System.Threading.Thread.Sleep(500);
                    //在释放前需要按步骤清理音视频模块和nim client模块
                    NIM.VChatAPI.Cleanup();
                }

                if (!_beKicked)
                {
                    System.Threading.Semaphore s = new System.Threading.Semaphore(0, 1);
                    NIM.ClientAPI.Logout(NIM.NIMLogoutType.kNIMLogoutAppExit, (r) =>
                    {
                        s.Release();
                    });
                    //需要logout执行完才能退出程序
                    s.WaitOne(TimeSpan.FromSeconds(10));
                    NIM.ClientAPI.Cleanup();
                }

                Application.Exit();
            }
        }
 public SemaphoreObject(string name, int maxCount, int freeCount, IntPtr formHandle, RichThread thread)
     : base(name, false, formHandle, thread)
 {
     this.maxCount = maxCount;
     this.freeCount = freeCount;
     this.waitHandle = new Semaphore(freeCount, maxCount);
 }
        public static void MultualExclusiongUsingSemaphore() {
            count = 0;
            Semaphore writeSem = new Semaphore(1, 1);
            answer.Clear();
            Random executionLengthRand = new Random();
            Thread[] threadArray = new Thread[1000];
            for (int i = 0; i < 1000; i++) 
            {
                threadArray[i] = new Thread(
                        () =>
                        {
                            int temp = -1;
                            executionLengthRand.Next(697);
                            writeSem.WaitOne();
                            count = count + 1;
                            temp = count;
                            executionLengthRand.Next(1937);
                            writeSem.Release();
                            answer.Push(temp);
                        }
                    );

                threadArray[i].Start();
            }

            foreach (var t in threadArray)
            {
                t.Join();
            }

            foreach (var item in answer.Reverse()) 
            {
                Console.WriteLine(item);
            }
        }
Beispiel #10
0
        public Hokuyo(LidarID lidar)
        {
            //trameDetails = "VV\n00P\n";
            this.lidar = lidar;
            semLock = new Semaphore(1, 1);

            switch (lidar)
            {
                case LidarID.LidarSol: model = "URG-04LX-UG01"; break;
            }

            if (model.Contains("UBG-04LX-F01"))//Hokuyo bleu
            {
                nbPoints = 725;
                angleMesurable = new Angle(240, AnglyeType.Degre);
                offsetPoints = 44;
            }
            else if (model.Contains("URG-04LX-UG01")) //Petit hokuyo
            {
                nbPoints = 725;
                angleMesurable = new Angle(240, AnglyeType.Degre);
                offsetPoints = 44;
            }
            else if (model.Contains("BTM-75LX")) // Grand hokuyo
            {
                nbPoints = 1080;
                angleMesurable = new Angle(270, AnglyeType.Degre);
                offsetPoints = 0;
            }

            position = Robots.GrosRobot.Position;

            Robots.GrosRobot.PositionChange += GrosRobot_PositionChange;
        }
Beispiel #11
0
 private 信号量管理()
 {
     m_b实例 = true;
     m_信号量实例 = null;
     m_软启多任务信号量 = new Semaphore(0, 1);
     m_命令信号量 = new Semaphore(0, 1);
 }
        public override bool Execute()
        {
            if (File.Exists(PropsFile) && File.Exists(TargetsFile))
            {
                return true;
            }

            string semaphoreName = PropsFile.ToUpper().GetHashCode().ToString("X");

            bool releaseSemaphore;

            using (Semaphore semaphore = new Semaphore(0, 1, semaphoreName, out releaseSemaphore))
            {
                try
                {
                    if (!releaseSemaphore)
                    {
                        releaseSemaphore = semaphore.WaitOne(TimeSpan.FromMinutes(5));

                        return releaseSemaphore;
                    }

                    return GenerateBuildPackageImportFile();
                }
                finally
                {
                    if (releaseSemaphore)
                    {
                        semaphore.Release();
                    }
                }
            }
        }
        /*Object Parent;

        public ProcessBaseImplThreads(Object Parent)
        {
            this.Parent = Parent;
        }*/
        public void Init(RunDelegate Delegate)
        {
            //Console.WriteLine("Init(" + Parent + ")");

            if (mainThread == null)
            {
                SemaphoreGlobal = new Semaphore(1, 1);
                SemaphoreGlobal.WaitOne();

                mainThread = Thread.CurrentThread;
                //mainMutex.WaitOne();
            }

            Semaphore = new Semaphore(1, 1);
            Semaphore.WaitOne();
            currentThread = new Thread(delegate()
            {
                Semaphore.WaitOne();
                //currentThread.Interrupt();
                Delegate();
            });

            currentThread.Start();

            //Mutex.WaitOne();
        }
Beispiel #14
0
        //Constructor
        public SoundEffects(ref AxWindowsMediaPlayer axMedia, ref Semaphore soundSem, ref Semaphore mediaSem, ref Boolean stop)
        {
            //Assign variables
            soundSemaphore = soundSem;
            mediaSemaphore = mediaSem;
            media = axMedia;
            media.settings.setMode("loop", false);
            stopped = stop;

            //Determine if sound folder already exists
            if (!Directory.Exists(currentDirectory))
            {
                try
                {
                    Directory.CreateDirectory(currentDirectory); //if not, create it
                } catch { }
            }
            //Get the length of every sound file
            MaxTurboLength = GetSoundLength(currentDirectory + "\\MaxTurbo.wav") + 1000;
            Start1Length = GetSoundLength(currentDirectory + "\\Start1.wav") + 1000;
            Start2Length = GetSoundLength(currentDirectory + "\\Start2.wav") + 1000;
            LoopLength = GetSoundLength(currentDirectory + "\\Loop.wav") + 1000;
            StopLength = GetSoundLength(currentDirectory + "\\Stop.wav") + 1000;
            sound = new System.Media.SoundPlayer(currentDirectory + "\\MaxTurbo.wav");
        }
Beispiel #15
0
        public Plateau()
        {
            if (!Config.DesignMode)
            {
                EtapeDune = 0;
                Elements = new Elements();
                ObstaclesPieds = new IForme[0];
                RayonAdversaireInitial = 200;
                RayonAdversaire = RayonAdversaireInitial;

                ReflecteursNosRobots = true;

                ObstaclesBalise = new List<IForme>();

                ChargerObstacles();
                CreerSommets(110);
                SauverGraph();

                //ChargerGraph();

                Balise.PositionEnnemisActualisee += Balise_PositionEnnemisActualisee;
                    //SuiviBalise.PositionEnnemisActualisee += new Balises.SuiviBalise.PositionEnnemisDelegate(interpreteBalise_PositionEnnemisActualisee);
                InitElementsJeu();

                Random random = new Random();

                SemaphoreCollisions = new Semaphore(0, int.MaxValue);
                thCollisions = new Thread(ThreadTestCollisions);
                thCollisions.Start();
            }
        }
 public Gateway()
 {
     gateClosed = false;
     gateSemaphore = new Semaphore(1, 1);
     numberOfGateClosers = 0;
     gateControlSemaphore = new Semaphore(1, 1);
 }
 private ThreadPool(int queueSize, int threadNum)
 {
     #if UNITY_WEBPLAYER
     threadNum = 1;
     #else
     if (threadNum == 0)
     {
         threadNum = SystemInfo.processorCount;
     }
     #endif
     m_threadPool = new Thread[threadNum];
     m_taskQueue = new TaskInfo[queueSize];
     m_nPutPointer = 0;
     m_nGetPointer = 0;
     m_numTasks = 0;
     m_putNotification = new AutoResetEvent(false);
     m_getNotification = new AutoResetEvent(false);
     #if !UNITY_WEBPLAYER
     if (1 < threadNum)
     {
         m_semaphore = new Semaphore(0, queueSize);
         for (int i = 0; i < threadNum; ++i)
         {
             m_threadPool[i] = new Thread(ThreadFunc);
             m_threadPool[i].Start();
         }
     }
     else
     #endif
     {
         m_threadPool[0] = new Thread(SingleThreadFunc);
         m_threadPool[0].Start();
     }
 }
Beispiel #18
0
 public FormProgressWindows()
 {
     _setErrorList = new HashSet<int>();
     _bIgnoreError = false;
     _semaPause = new System.Threading.Semaphore(0, 1);
     InitializeComponent();
 }
 public WordCounter(ILogger logger, IConfig config)
 {
     _activeUserRequests = new Dictionary<string, Task>();
     _servedUserRequests = new Semaphore(MAX_ACTIVE_USER_REQUESTS, MAX_ACTIVE_USER_REQUESTS);
     _logger = logger;
     _config = config;
 }
 private void WriteToFile()
 {
     using System.Threading.Semaphore semaphore = new System.Threading.Semaphore(1, 1, "OS-übergreifende Semaphore");
     semaphore.WaitOne();
     File.AppendAllText(_fileName, $"{nameof(Semaphore)}: {DateTime.Now:hh:mm:ss:ffff} {Environment.NewLine}");
     semaphore.Release();
 }
Beispiel #21
0
 public Sender(List <byte[]> list, int parallelThreads, IPAddress ipaddress, int port)
 {
     _list      = list;
     S          = new System.Threading.Semaphore(parallelThreads, parallelThreads);
     _ipaddress = ipaddress;
     _port      = port;
 }
Beispiel #22
0
        public OutProcessHost(MachineType type, string currentDirectory, string path)
        {
            if (currentDirectory == null)
                currentDirectory = Directory.GetCurrentDirectory();

            string lrpHostPath = null;
            if (type == MachineType.IMAGE_FILE_MACHINE_I386)
            {
                this.isPtr32Bit = true;
                lrpHostPath = FilesResolver.LrpX86HostPath;
            }
            else if (type == MachineType.IMAGE_FILE_MACHINE_AMD64)
            {
                this.isPtr32Bit = false;
                lrpHostPath = FilesResolver.LrpX64HostPath;
            }
            else
            {
                var message = string.Format("Unsupported machine type = {0}", type);
                throw new ArgumentException(message, "type");
            }

            this.pipId = Guid.NewGuid().ToString();

            using (var semaphore = new Semaphore(0, 1, this.pipId))
            {
                var args = string.Format("\"{0}\" {1} \"{2}\"", currentDirectory, this.pipId, path);
                var process = Process.Start(lrpHostPath, args);
                process.Dispose();
                if (!semaphore.WaitOne(PipeWaitingTimeout))
                    throw new TimeoutException("Timeout of LRP host waiting has been reached.");
            }

            var pipeName = @"\\.\pipe\" + this.pipId;

            if (!WinAPI.WaitNamedPipe(pipeName, PipeWaitingTimeout))
                throw new TimeoutException("Timeout of pipe waiting has been reached.");

            this.pipe = WinAPI.CreateFile(pipeName, WinAPI.GENERIC_READ | WinAPI.GENERIC_WRITE, 0, IntPtr.Zero, WinAPI.OPEN_EXISTING, 0, IntPtr.Zero);
            if (this.pipe == WinAPI.INVALID_HANDLE)
                throw new Exception("Couldn't open pipe");

            using (var transaction = new Transaction(this))
            {
                var buffer = this.ReadBuffer();
                var isValid = buffer.ReadBoolean();
                if (isValid)
                {
                    this.signature = buffer.ReadAString();
                }
                else
                {
                    var error = buffer.ReadInt32();
                    var message = buffer.ReadAString();
                    throw new Win32Exception(error, message);
                }

                transaction.Commit();
            }
        }
Beispiel #23
0
        public Runner()
        {
            Console.Write("TestDvDeviceCs - starting\n");

            DeviceBasic device = new DeviceBasic();
            iDeviceList = new List<CpDevice>();
            CpDeviceList.ChangeHandler added = new CpDeviceList.ChangeHandler(DeviceAdded);
            CpDeviceList.ChangeHandler removed = new CpDeviceList.ChangeHandler(DeviceRemoved);
            CpDeviceListUpnpServiceType list = new CpDeviceListUpnpServiceType("openhome.org", "TestBasic", 1, added, removed);
            Semaphore sem = new Semaphore(0, 1);
            sem.WaitOne(1000);
            Debug.Assert(iDeviceList.Count == 1);
            TestBasicCp cp = new TestBasicCp(iDeviceList[0]);
            cp.TestActions();
            cp.TestSubscriptions();
            list.Dispose();
            lock (this)
            {
                for (int i = 0; i < iDeviceList.Count; i++)
                {
                    iDeviceList[i].RemoveRef();
                }
            }
            device.Dispose();

            Console.Write("TestDvDeviceCs - completed\n");
        }
Beispiel #24
0
        public static void Main()
        {
            const int count = 4;

            _desk = new Semaphore(0, count - 1);

            var forks = new List<Fork>(count);
            var philosophers = new List<Philosopher>(count);

            for (var i = 0; i < count; i++)
            {
                forks.Add(new Fork {Number = i});
            }

            philosophers.Add(new Philosopher(_desk, count - 1) { LeftFork = forks[count - 1], RightFork = forks[0], Number = 0, HungerLevel = 0 });

            for (var i = 1; i < count; i++)
            {
                philosophers.Add(new Philosopher(_desk, count - 1) { LeftFork = forks[i - 1], RightFork = forks[i], Number = i, HungerLevel = count - 1 });
            }

            var tasks = new Task[count];

            for (var i = 0; i < count; i++)
            {
                var idx = i;
                tasks[idx] = new Task(() => philosophers[idx].Start());
            }

            _desk.Release(count - 1);
            Parallel.ForEach(tasks, t => t.Start());

            Console.ReadKey();
        }
Beispiel #25
0
 public Fork(int index)
 {
     _index = index;
     _forkLock = new Semaphore(1, 1);
     _isTaken = false;
     _isForEat = true;
 }
        /// <summary>
        /// Konstruktor bezparametryczny
        /// </summary>
        public WidokMiniatur()
        {
            WyswietloneZdjecia = new List<IZdjecie>();
            WszystkieZdjecia = new List<IZdjecie>();
            katalogi = new Katalog[0];
            tagi = new List<long>();
            LargeImageList = new ImageList();
            LargeImageList.ColorDepth = System.Windows.Forms.ColorDepth.Depth32Bit;
            LargeImageList.Tag = "100%";
            LargeImageList.TransparentColor = System.Drawing.Color.Transparent;
            LargeImageList.ImageSize = new Size(Config.RozmiarMiniatury + 2, Config.RozmiarMiniatury + 2);

            //Activate double buffering

            //Enable the OnNotifyMessage event so we get a chance to filter out
            // Windows messages before they get to the form's WndProc
            this.SetStyle(ControlStyles.OptimizedDoubleBuffer | ControlStyles.AllPaintingInWmPaint, true);
            this.SetStyle(ControlStyles.EnableNotifyMessage, true);

            katalog = Properties.Resources.katalog;
            katalog_do_gory = Properties.Resources.katalog_do_gory;
            Edycja = false;

            sem = new Semaphore(0, 1);
            sem.Release();
        }
 public SocketEventClient(string id, string url)
 {
     this.ClientId = id;
     this.Url = url;
     this.eventStore = new ConcurrentDictionary<string, dynamic>();
     this.locker = new Semaphore(1, 1);
 }
Beispiel #28
0
        public MySqlPool(MySqlConnectionStringBuilder settings)
        {
            minSize = settings.MinimumPoolSize;
            maxSize = settings.MaximumPoolSize;
            if (minSize > maxSize)
            {
                minSize = maxSize;
            }
            this.settings = settings;
#if NET20
            inUsePool = new List <Driver>((int)maxSize);
            idlePool  = new Queue <Driver>((int)maxSize);
#else
            inUsePool = new ArrayList((int)maxSize);
            idlePool  = new Queue((int)maxSize);
#endif

            // prepopulate the idle pool to minSize
            for (int i = 0; i < minSize; i++)
            {
                Driver d = Driver.Create(settings);
                d.Pool = this;
                idlePool.Enqueue(d);
            }

            procedureCache = new ProcedureCache((int)settings.ProcedureCacheSize);
            poolGate       = new Semaphore(0, int.MaxValue);
            counter        = (int)maxSize;

            // we don't really need to create this but it makes the code a bit cleaner
            lockObject = new Object();
        }
        public override void EndScene()
        {
            try
            {
                if (form.Settings.RecentSplits.Any())
                    config.SetString("splitspath", form.Settings.RecentSplits.Last().Path);
                if (form.Settings.RecentLayouts.Any())
                    config.SetString("layoutpath", form.Settings.RecentLayouts.Last());

                var sem = new Semaphore(0, 1);
                Action formCloseAction = () =>
                    {
                        form.TopMost = false;

                        while (form.Visible)
                            form.Close();
                        sem.Release();
                    };

                if (form.InvokeRequired)
                    form.Invoke(formCloseAction);
                else
                    formCloseAction();

                sem.WaitOne();
            }
            catch (Exception ex)
            {
                Log.Error(ex);

                API.Instance.Log(ex.Message);
                API.Instance.Log(ex.StackTrace);
            }
        }
Beispiel #30
0
 public FormProgressWindows()
 {
     _setErrorList = new HashSet <int>();
     _bIgnoreError = false;
     _semaPause    = new System.Threading.Semaphore(0, 1);
     InitializeComponent();
 }
        /// <summary>
        /// Initializes the a new instance of the pool. 
        /// </summary>
        /// <param name="threadCount">The number of threads in the pool.</param>
        /// <param name="taskCountLimit">The maximal number of tasks that can be accepted simultaneously.</param>
        public BlockingThreadPool(int threadCount, int taskCountLimit)
        {
            if (threadCount <= 0)
            {
                throw new ArgumentException($"Parameter {nameof(threadCount)} should be greater than zero.", nameof(threadCount));
            }
            if (taskCountLimit < threadCount)
            {
                throw new ArgumentException($"Parameter {nameof(taskCountLimit)} should be greater or equal to {nameof(threadCount)}.", nameof(taskCountLimit));
            }

            taskQueue = new Queue<Action>(taskCountLimit);
            enqueSemaphore = new Semaphore(taskCountLimit, taskCountLimit + 1);
            dequeSemaphore = new Semaphore(0, taskCountLimit + 1);
            running = true;
            disposed = false;
            threads = new Thread[threadCount];
            for (int i = 0; i < threadCount; i++)
            {
                Thread thread = new Thread(WorkerThreadLoop);
                threads[i] = thread;

                thread.Name = "Thread#" + i;
                thread.IsBackground = true;

                thread.Start();
            }
        }
Beispiel #32
0
        public WorkerResult StartUnmanaged()
        {
            WorkerResult ret = null;
            Unmanaged worker = new Unmanaged();
            Semaphore locker = new Semaphore(0, 1);

            worker.OnCallback += (IEntity param) =>
            {
                ret = param as WorkerResult;

                if (ret == null)
                {
                    Console.WriteLine("erro no cast!");
                }
                else
                {
                    Console.WriteLine("Id da classe: {0}", ret.Id);
                }
                locker.Release();
            };

            worker.DoSomething(2);
            Console.WriteLine("Chamou o Unmanaged....");

            locker.WaitOne();

            return ret;
        }
Beispiel #33
0
        public readonly static string MainMutexName; // = "relaxtime.8vs.ru|" + BitConverter.ToString(System.Text.Encoding.Unicode.GetBytes(Application.StartupPath)).Replace("-", "");

        static Program()
        {
            var sha = new keccak.SHA3(1024);

            MainMutexName = "relaxtime.8vs.ru|" + BitConverter.ToString(sha.getHash224(System.Text.Encoding.Unicode.GetBytes(AppDomain.CurrentDomain.BaseDirectory))).Replace("-", "");
            m             = new System.Threading.Semaphore(1, 1, MainMutexName);
        }
Beispiel #34
0
        private readonly Semaphore _tracker; //todo: semaphore a little heavy?

        #endregion Fields

        #region Constructors

        public PooledConnectionProvider(ConnectionStringBuilder builder)
        {
            _builder = builder;
            _idlePool = new Queue<IConnection>(builder.PoolSize);
            _tracker = new Semaphore(builder.PoolSize, builder.PoolSize);
            _timeout = builder.Timeout*1000;
        }
Beispiel #35
0
        /// <summary>
        /// Analogiczna dla WaitHandle.WaitAll - wymuś uzyskanie kilku dostępów na semaforze. Po uzyskaniu tej liczby dostępów, zwolnij je
        /// wszystkie. Funkcja do tego czasu blokuje.
        /// </summary>
        /// <param name="semaphore">Semafor</param>
        /// <param name="waitCount">Ile użyć na semaforze</param>
        public static void waitFullSemaphore(Semaphore semaphore, int waitCount)
        {
            for (int i = 0; i < waitCount; i++)
                semaphore.WaitOne();

            semaphore.Release(waitCount);
        }
		public BotFramework(IBotFrameworkOutputHandler outputHandler, ArgumentsParser parsedArgs)
		{
			_outputHandler = outputHandler;
			if(outputHandler == null || parsedArgs == null)
				throw new ArgumentNullException("One or more arguments to framework is null", new Exception());

			var numberOfBots = parsedArgs.NumBots;
			var simultaneousBots = parsedArgs.SimultaneousBots;
			var host = parsedArgs.Host;
			var port = parsedArgs.Port;

			if (numberOfBots > NUM_BOTS_MAX || simultaneousBots > NUM_BOTS_MAX || simultaneousBots > numberOfBots)
				throw new ArgumentException("Too many bots requested");

			if (numberOfBots <= 0 || simultaneousBots <= 0)
				throw new ArgumentException("Not enough bots requested");

			_numBots = numberOfBots;
			_host = host;
			_port = port;

			_botsList = new List<IBot>(numberOfBots);

			_doneSignal = new Semaphore(simultaneousBots, simultaneousBots);
		}
        public SynchronizationContextMock()
        {
            CallQueued = new Semaphore(0, Int32.MaxValue);
            m_WorkItemQueue = new Queue<WorkItem>();

            m_WorkerThread = new WorkerThread("SynchronizationContextMockThread", this);
        }
Beispiel #38
0
 public Portal(string portalName) : base(portalName)
 {
     this.routingTable      = new Hashtable();
     this._semaphore        = new System.Threading.Semaphore(0, 0x7fffffff);
     this.connected         = false;
     this.socket            = false;
     this.unregisteredAgent = new List <MetaAgent>();
 }
Beispiel #39
0
        protected override void OnStart(string[] args)
        {
            sem = new System.Threading.Semaphore(0, 1, "BatteryStatusChanging");
            sem.Release();
            Thread ServiceThread = new Thread(new ThreadStart(eventWait));

            ServiceThread.Start();
        }
Beispiel #40
0
 public QueueParticipant(int id, System.Threading.Semaphore semaphore, int moneyToSpend, Shop que, System.Threading.Barrier barrier)
 {
     this.id           = id;
     this.que          = que;
     this.semaphore    = semaphore;
     this.moneyToSpend = moneyToSpend;
     this.barrier      = barrier;
 }
Beispiel #41
0
 // :$$$.отдатьсемафор
 private static bool releaseSemaphore(System.Threading.Semaphore s, int p)
 {
     for (int i = 0; i < p; i++)
     {
         s.Release();
     }
     return(true);
 }
Beispiel #42
0
        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                _ThrottlingSemaphore?.Dispose();
                _ThrottlingSemaphore = null;
            }

            base.Dispose(disposing);
        }
Beispiel #43
0
        public Form1()
        {
            InitializeComponent();
            Set_max();
            list = new Dictionary <int, int>();
            thd  = new List <Thread>();
            prev = (int)numericUpDown1.Value;

            Sem     = new System.Threading.Semaphore(prev, 10);
            numeric = 0;
        }
        public MainWindow()
        {
            if (isFirst == true)
            {   // 初回起動時の処理
                // MainWindowの二重起動防止
                // 初回のみセマフォを生成
                _pool = new System.Threading.Semaphore(1, 1, SemaphoreName,
                                                       out createdNew);
            }

            if (_pool.WaitOne(0, false) == false)
            {   // セマフォ取得済みの場合MainWindowを起動しない
                // 既存のMainWindowをアクティブにする
                currentWindow.WindowState = WindowState.Normal;
                currentWindow.Activate();
                // NotifyIconWrapperに通知するため、二重起動発生フラグを立てる
                isDoubleBoot = true;
                return;
            }
            // 現在起動しているMainWindowのオブジェクトを保存
            currentWindow = this;

            InitializeComponent();

            // スケジュール情報を初期化
            Schedules schedules = new Schedules();

            schedules.mySchedules = new List <Schedule>();

            // スケジュール情報をロード
            ReadFromFile(ref schedules);

            // 通知アイテムリスト(listBox1にスケジュール情報を格納)
            foreach (Schedule s in schedules.mySchedules)
            {
                listBox1.Items.Add(s);
            }

            // 直近のリマインド項目をタイマーセット
            SetNextTimerEvent();

            // 起動時にこのウィンドウを開かないチェックボックスを確認
            checkBox2.IsChecked = Properties.Settings.Default.firstBootWindow;
            if ((isFirst == true) &&
                (checkBox2.IsChecked == true))
            {
                Close();
            }

            // 初回フラグを更新
            isFirst = false;
        }
Beispiel #45
0
        /// <summary>
        /// Full constructor.
        /// </summary>
        /// <param name="maxConcurrentRequests">The maximum number of concurrent requests allowed. Must be greater than zero</param>
        /// <param name="innerHandler">The next handler in the pipeline to pass the request onto.</param>
        /// <exception cref="System.ArgumentOutOfRangeException">Thrown if <paramref name="maxConcurrentRequests"/> is less than or equal to zero.</exception>
        /// <exception cref="System.ArgumentNullException">Thrown if <paramref name="innerHandler"/> parameter is null.</exception>
        public ThrottledConcurrentRequestHandler(int maxConcurrentRequests, System.Net.Http.HttpMessageHandler innerHandler) : base(innerHandler)
        {
            if (maxConcurrentRequests <= 0)
            {
                throw new ArgumentOutOfRangeException(nameof(maxConcurrentRequests));
            }
            if (innerHandler == null)
            {
                throw new ArgumentNullException(nameof(innerHandler));
            }

            _ThrottlingSemaphore = new System.Threading.Semaphore(maxConcurrentRequests, maxConcurrentRequests);
        }
Beispiel #46
0
        /// <summary>
        /// Full constructor.
        /// </summary>
        /// <param name="maxConcurrentRequests">The maximum number of concurrent requests allowed. Must be greater than zero</param>
        /// <param name="innerHandler">The next handler in the pipeline to pass the request onto.</param>
        /// <exception cref="System.ArgumentOutOfRangeException">Thrown if <paramref name="maxConcurrentRequests"/> is less than or equal to zero.</exception>
        /// <exception cref="System.ArgumentNullException">Thrown if <paramref name="innerHandler"/> parameter is null.</exception>
        public ThrottledConcurrentRequestsFilter(int maxConcurrentRequests, IHttpFilter innerHandler)
        {
            if (maxConcurrentRequests <= 0)
            {
                throw new ArgumentOutOfRangeException(nameof(maxConcurrentRequests));
            }
            if (innerHandler == null)
            {
                throw new ArgumentNullException(nameof(innerHandler));
            }

            _ThrottlingSemaphore = new System.Threading.Semaphore(maxConcurrentRequests, maxConcurrentRequests);
            _InnerHandler        = innerHandler;
        }
        // '' <summary>
        // '' Constructs a new HTTP server given a desired web root path.
        // '' </summary>
        // '' <param name="rootPath"></param>
        // '' <remarks></remarks>
        private Server(string rootPath)
        {
            WebRoot = rootPath;
            LoadConfig();
            const int maxConnections = 10000;
            //  pull this from the config, but for now we just make them usable
            const int receiveBufferSize = 4096;

            //  pull this from the config, but for now we just make them usable
            _maxConnections = maxConnections;
            _bufferManager  = new BufferManager((receiveBufferSize
                                                 * (_maxConnections * 2)), receiveBufferSize);
            _readWritePool            = new SocketAsyncEventArgsPool(_maxConnections);
            _maxNumberAcceptedClients = new Threading.Semaphore(_maxConnections, _maxConnections);
        }
Beispiel #48
0
        static void Main(string[] args)
        {
            var connectionNumber = int.Parse(ConfigurationManager.AppSettings["connectionNumber"]);

            Console.WriteLine("Connecting...");

            m_Sockets          = new Socket[connectionNumber];
            m_ConnectSemaphore = new Semaphore(0, connectionNumber);

            for (var i = 0; i < connectionNumber; i++)
            {
                var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                socket.BeginConnect(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 2012), OnClientConnected, Tuple.Create(socket, i));
            }

            var finishConnect = 0;

            while (finishConnect < connectionNumber)
            {
                m_ConnectSemaphore.WaitOne();
                finishConnect++;
            }

            var connected = m_Sockets.Count(s => s != null);

            Console.WriteLine("{0} connected, {1} not connected!", connected, m_Sockets.Length - connected);

            m_Timer = new Timer(OnTimerCallback, null, 5000, 5000);

            while (true)
            {
                var line = Console.ReadLine();

                if (line.Equals("quit", StringComparison.OrdinalIgnoreCase))
                {
                    m_Stopped = true;
                    break;
                }
            }

            if (m_Timer != null)
            {
                m_Timer.Change(Timeout.Infinite, Timeout.Infinite);
            }

            Thread.Sleep(2000);
        }
Beispiel #49
0
        // :$$$.семафор
        private static int blockSemaphore(System.Threading.Semaphore s, int p)
        {
            int i = 0;

            try
            {
                // int count = p;
                for (; i < p; i++)
                {
                    // Console.WriteLine("wait");
                    s.WaitOne();
                    // Console.WriteLine("waited " + --count);
                }
                return(i);
            }
            catch
            {
                return(i);
            }
        }
        /// <summary>Initializes the thread pool</summary>
        static AffineThreadPool()
        {
            // Create our thread stores; we handle synchronization ourself
            // as we may run into situations where multiple operations need to be atomic.
            // We keep track of the threads we've created just for good measure; not actually
            // needed for any core functionality.
#if XBOX360 || WINDOWS_PHONE
            workAvailable = new Semaphore();
#else
            workAvailable = new System.Threading.Semaphore(0, int.MaxValue);
#endif
            userWorkItems = new Queue <UserWorkItem>(Processors * 4);
            workerThreads = new List <Thread>(Processors);
            inUseThreads  = 0;

#if XBOX360
            // We can only use these hardware thread indices on the XBox 360
            hardwareThreads = new Queue <int>(new int[] { 5, 4, 3, 1 });
#else
            // We can use all cores on a PC, starting from index 1
            hardwareThreads = new Queue <int>(Processors);
            for (int core = Processors; core >= 1; --core)
            {
                hardwareThreads.Enqueue(core);
            }
#endif

            // Create all of the worker threads
            for (int index = 0; index < Processors; index++)
            {
                // Create a new thread and add it to the list of threads.
                Thread newThread = new Thread(new ThreadStart(ProcessQueuedItems));
                workerThreads.Add(newThread);

                // Configure the new thread and start it
                newThread.Name         = "Nuclex.Support.AffineThreadPool Thread #" + index.ToString();
                newThread.IsBackground = true;
                newThread.Start();
            }
        }
Beispiel #51
0
        public Kernel(long frequency, int sysTmrIntNo, TMO sysTmrIntv)
        {
            m_Nucleus = new Nucleus(this, sysTmrIntNo, sysTmrIntv);

            m_Frequency            = frequency;
            m_OnSetEvent           = null;
            m_OnStart              = null;
            m_OnTerminate          = null;
            m_OnIdle               = null;
            m_OnOutput             = null;
            m_OnGetSystemTimeEvent = null;

            m_Thread      = null;
            m_Terminate   = false;
            m_IntEvent    = null;
            m_Locked      = 0;
            m_TaskMode    = false;
            m_TlsIndex    = new ThreadLocal <int>();
            m_SysSem      = new System.Threading.Semaphore(1, 1);
            m_CallbackSem = new System.Threading.Semaphore(1, 1);
            m_Lock        = 0;
        }
Beispiel #52
0
 public static bool TryOpenExisting(string name, out Semaphore result)
 {
     return(OpenExistingWorker(name, out result) == OpenExistingResult.Success);
 }
Beispiel #53
0
 private static OpenExistingResult OpenExistingWorker(string name, out Semaphore result)
 {
     throw new PlatformNotSupportedException(SR.PlatformNotSupported_NamedSynchronizationPrimitives);
 }
Beispiel #54
0
 public Semaphore(string name)
 {
     _lock = new System.Threading.Semaphore(1, 1, name);
     _lock.WaitOne();
 }
Beispiel #55
0
        public static void runExample1() // 로그파싱하는 example
        {
            List <string>          logTypes      = new List <string>();
            List <log_parsed_data> logParsedData = new List <log_parsed_data>();
            List <type_count_data> logTypesCnt   = new List <type_count_data>();

            System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();

            // read log  // parse log
            System.IO.StreamReader file = null;
            file = new System.IO.StreamReader(String.Format("{0}", inputFileNameQ1));
            string res;

            while ((res = file.ReadLine()) != null) // 한줄씩 읽어서 parse func에 밀어 넣음 // 결과는 list로 저장
            {
                parseLog(res, ref logParsedData);
            }
            // get log types count
            //Debug.Print("가져온 데이터 확인 ");
            for (int nIndex = 0; nIndex < logParsedData.Count; nIndex++) // list내 log type들 전부 가져옴
            {
                //단순한 string list
                logTypes.Add(logParsedData[nIndex].logType);
                //class list
                type_count_data data = new type_count_data();
                data.logType = logParsedData[nIndex].logType;
                logTypesCnt.Add(data);
            }
            // string list에서 중복제거
            logTypes = logTypes.Distinct().ToList();                         // 중복 제거해서 log type들을 가려냄
            // class list에서 중복제거 1
            logTypesCnt = logTypesCnt.Distinct(new TypeComparer()).ToList(); // 커스텀 비교자를 만들어서 중복제거에 적용
            // 이렇게 클래스 리스트 만들어서, 한번에 중복제거 정렬 까지 하면 코드 간편화 가능

            // 클래스 정렬
            logTypesCnt.Sort(delegate(type_count_data A, type_count_data B) // delegate로 정렬 구현
            {
                return(A.logType.CompareTo(B.logType));                     // 오름차순 문자 정렬 ABC->
            });

            // 각 타입별 로그 횟수 카운팅 (for문 돌려서 찾는 방법)
            for (int nIndex = 0; nIndex < logTypesCnt.Count; nIndex++)
            {
                Debug.WriteLine(logTypesCnt[nIndex].logType + " " + logTypesCnt[nIndex].count);

                foreach (log_parsed_data parsedDatTmp in logParsedData)
                {
                    if (logTypesCnt[nIndex].logType == parsedDatTmp.logType)
                    {
                        logTypesCnt[nIndex].count++;
                    }
                }
            }
            // List Method를 사용하여 각 타입별 로그 횟수 카운팅
            for (int nIndex = 0; nIndex < logTypesCnt.Count; nIndex++)
            {
                logTypesCnt[nIndex].count = logParsedData.FindAll(x => x.logType.Equals(logTypesCnt[nIndex].logType)).Count;
                // int count2 = logParsedData.Where(x => x.logType.StartsWith(logTypesCnt[nIndex].logType)).Count();
            }

            // 각 타입별 로그 횟수 카운팅 결과 파일로 출력
            System.IO.StreamWriter wfile = null;
            wfile = new System.IO.StreamWriter(String.Format(outputFileName, "1"), true);
            foreach (type_count_data t in logTypesCnt)
            {
                wfile.WriteLine(t.logType + "#" + t.count.ToString());
                Debug.WriteLine(t.logType + "#" + t.count.ToString());
                t.wfile_output = new System.IO.StreamWriter(String.Format(outputTypeLg, "1", t.logType), false); // 타입별 쓰기 핸들 미리열기//
            }
            //wfile.WriteLineAsync
            wfile.Close();

            sw.Start();
#if false
            // SYNC
            // 변환기 이용한 변환 수행
            //foreach (log_parsed_data parsedDatTmp in logParsedData)
            for (int nIndex = 0; nIndex < logParsedData.Count; nIndex++) // for문 써야 다시 값을 갱신하는데 편하다.
            {
                // 시간 오래 걸린다.
                logParsedData[nIndex].logDetail = runExternalProgram(external_progName, logParsedData[nIndex].logDetail).Replace("\r\n", string.Empty);
                // 타입 별 output 쓰기 (append모드)
                {
                    System.IO.StreamWriter wfile_type = null;
                    wfile_type = new System.IO.StreamWriter(String.Format(outputTypeLg, "1", logParsedData[nIndex].logType), true);
                    //foreach (type_count_data t in logTypesCnt)
                    {
                        wfile_type.WriteLine(logParsedData[nIndex].logTime + "#" + logParsedData[nIndex].logType + logParsedData[nIndex].logDetail);
                        //Debug.WriteLine(logParsedData[nIndex].logTime+"#"+ logParsedData[nIndex].logType+"#"+logParsedData[nIndex].logDetail);
                    }
                    //wfile.WriteLineAsync
                    wfile_type.Close();
                }
            }
#else
            //ASYNC
            max_thread = 100; // 최대 생성기능 쓰레드 갯수 리미트
            semaphore  = new System.Threading.Semaphore(max_thread, max_thread);

            List <Thread> threads = new List <Thread>();

            for (int nIndex = 0; nIndex < logParsedData.Count; nIndex++) // for문 써야 다시 값을 갱신하는데 편하다.
            {
                log_parsed_data t = new log_parsed_data();
                t = logParsedData[nIndex];
                //t.Print();
                //Parallel.For(0, 100, new ParallelOptions { MaxDegreeOfParallelism = 100 }, (i)=> runAsyncProc(t));

                //System.Threading.ThreadPool.QueueUserWorkItem((state) =>
                //{
                semaphore.WaitOne(); // 세마포어 wait
                try
                {
                    var thread = new System.Threading.Thread(() => runAsyncProc(t, logTypesCnt));
                    threads.Add(thread);
                    thread.Start();
                }
                finally
                {
                    semaphore.Release(); // 세마포어 end
                }
                //});
            }
#endif
            // Await threads
            foreach (Thread thread in threads)
            {
                thread.Join();
            }

            sw.Stop();
            Debug.WriteLine("elasped time:" + sw.ElapsedMilliseconds.ToString() + "mSec");
            int test = 0;
        }
Beispiel #56
0
 public double[] threadSafeEvaluateNetwork(INetwork network, System.Threading.Semaphore sem)
 {
     throw new Exception("The method or operation is not implemented.");
 }
Beispiel #57
0
        private void ProcessFiles()
        {
            bool pastaGeral = false;

            foreach (var item in Directorys)
            {
                string directory = item;
                if (directory.ToLower().EndsWith("\\geral"))
                {
                    pastaGeral = true;
                }
            }
            int emp = (pastaGeral ? -1 : Empresas.FindEmpresaByThread());

            string arqTemp = "";

            CancelProcess = false;

            // Create a semaphore that can satisfy up to three
            // concurrent requests. Use an initial count of zero,
            // so that the entire semaphore count is initially
            // owned by the main program thread.
            //
            _pool = new System.Threading.Semaphore(10, 20);

            while (!CancelProcess)
            {
                try
                {
                    foreach (var item in Directorys)
                    {
                        Directory = item;

                        if (!String.IsNullOrEmpty(Directory) && System.IO.Directory.Exists(Directory))
                        {
                            DirectoryInfo dirInfo = new DirectoryInfo(Directory);
                            FileInfo[]    files   = dirInfo.GetFiles("*.*", SearchOption.TopDirectoryOnly)
                                                    .Where(s => Filter.Contains(s.Extension.ToLower()))
                                                    .OrderBy(o => o.CreationTime)
                                                    .ToArray();             //Retorna o conteúdo já ordenado por data de modificação, do menor para o maior. Wandrey 26/03/2015

                            if (files != null)
                            {
                                if (files.Length > 0)
                                {
                                    //cria todos os fileinfos
                                    foreach (FileInfo fi in files)
                                    {
                                        if (CancelProcess)
                                        {
                                            break;
                                        }

                                        if (File.Exists(fi.FullName))
                                        {
                                            if (!Functions.FileInUse(fi.FullName))
                                            {
                                                arqTemp = fi.DirectoryName + "\\Temp\\" + fi.Name;
                                                Functions.Move(fi.FullName, arqTemp);
                                                RaiseFileChanged(new FileInfo(arqTemp), emp);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    Auxiliar.WriteLog(ex.Message + "\r\n" + ex.StackTrace, false);
                    if (emp >= 0)
                    {
                        Functions.GravarErroMover(arqTemp, Empresas.Configuracoes[emp].PastaXmlRetorno, ex.ToString());
                    }
                }
                finally
                {
                    if (!CancelProcess)
                    {
                        Thread.Sleep(1000);
                    }
                }
            }
        }
Beispiel #58
0
 public void Dispose()
 {
     _ThrottlingSemaphore?.Dispose();
     _ThrottlingSemaphore = null;
 }
Beispiel #59
0
 public MyClass_Thread()
 {
     max_thread = 100; // 최대 생성기능 쓰레드 갯수 리미트
     semaphore  = new System.Threading.Semaphore(this.max_thread, this.max_thread);
 }
Beispiel #60
0
 public Johannes(DirectoryInfo rootDir, int parallelThreads)
 {
     _rootDir = rootDir;
     S        = new System.Threading.Semaphore(parallelThreads, parallelThreads);
 }