상속: System.MarshalByRefObject, IDisposable
예제 #1
0
 private void OnConnectPeer()
 {
     Console.WriteLine("Connecting to Peer @ {0}:{1}", PeerHost, PeerPort);
     ConnectedToPeer = false;
     for (var i = 0; i < MAX_Connect_Attempts && !ConnectedToPeer; i++)
     {
         Console.Write("C");
         Peer = new TcpClient();
         Task ar = Peer.ConnectAsync(PeerHost, PeerPort);
         System.Threading.WaitHandle wh = ((IAsyncResult)ar).AsyncWaitHandle;
         bool signaled = wh.WaitOne(TimeSpan.FromMilliseconds(1200));
         if (!signaled || !Peer.Connected)
         {
             Console.Write("x");
         }
         else
         {
             ConnectedToPeer = true;
         }
     }
     if (ConnectedToPeer)
     {
         Console.WriteLine("\nConnected to {0}:{1}, start sending ping...", PeerHost, PeerPort);
         stateMachine.FireAsync(Trigger.ConnectedToPeer);
     }
     else
     {
         Console.WriteLine(" - couldn't reach to peer");
         stateMachine.FireAsync(Trigger.FailedToPeer);
     }
 }
 protected override void DoProcess(ProcessItemHandler handler)
 {
     if (!this.UsePipes)
     {
         this.ProcessExtract(handler);
     }
     else
     {
         WaitHandle[] waitHandles = new WaitHandle[] { this.FinishedEvent, this.BeforeExtractItem };
         ThreadPool.QueueUserWorkItem(new WaitCallback(this.ProcessExtract));
         AsyncProcessWcxItemEventArgs e = new AsyncProcessWcxItemEventArgs(this);
         while (true)
         {
             if (WaitHandle.WaitAny(waitHandles) == 0)
             {
                 break;
             }
             this.ExtractNeeded = false;
             handler(e);
             if (e.Cancel)
             {
                 this.TerminateEvent.Set();
             }
             else if (!this.ExtractNeeded)
             {
                 this.ConfirmExtractItem.Set();
             }
         }
     }
     if (this.ProcessResult != 0)
     {
         WcxErrors.ThrowExceptionForError(this.ProcessResult);
     }
 }
예제 #3
0
        private bool IsConnected(string ipAddress)
        {
            bool connected = false;

            using (TcpClient client = new TcpClient()) {
                IAsyncResult ar = client.BeginConnect(ipAddress, 9100, null, null);
                System.Threading.WaitHandle wh = ar.AsyncWaitHandle;
                try {
                    if (!ar.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(1), false))
                    {
                        client.Close();
                        connected = false;
                        throw new TimeoutException();
                    }

                    client.EndConnect(ar);
                    connected = true;
                } catch (Exception ex) {
                    return(false);
                } finally {
                    wh.Close();
                }

                client.Close();
            }

            return(connected);
        }
예제 #4
0
파일: Utils.cs 프로젝트: khaha2210/radio
      public static WaitReturn WaitForComplete(double mill, WaitHandle wh)
      {
         TimeSpan goal = new TimeSpan(DateTime.Now.AddMilliseconds(mill).Ticks);
         MSG msg = new MSG();
         HandleRef h = new HandleRef(null, IntPtr.Zero);

         do
         {
            if(PeekMessage(out msg, h, 0, 0, PM_REMOVE))
            {
                  TranslateMessage(ref msg);
                  DispatchMessage(ref msg);
               }

            if(wh.WaitOne(new TimeSpan(1), false))
            {
               return WaitReturn.Complete;
            }

            if(goal.CompareTo(new TimeSpan(DateTime.Now.Ticks)) < 0)
            {
               return WaitReturn.Timeout;
            }

         } while(true);
      }
        public static void Synchronize(params object[] threadResults)
        {
            WaitHandle[] waitHandles = new WaitHandle[threadResults.Length];
            for (int i = 0; i < threadResults.Length; i++)
            {
                waitHandles[i] = ((IThreadedResult)threadResults[i]).WaitHandle;
            }

            ApartmentState apartmentState = Thread.CurrentThread.GetApartmentState();
            if (apartmentState == ApartmentState.MTA)
            {
                WaitHandle.WaitAll(waitHandles);
                return;
            }

            if (apartmentState == ApartmentState.STA)
            {
                foreach (WaitHandle myWaitHandle in waitHandles)
                {
                    WaitHandle.WaitAny(new WaitHandle[] { myWaitHandle });
                }
                return;
            }

            throw new UnhandledThreadApartmentState(apartmentState);
        }
예제 #6
0
		public void TestQueryWithContainsInParallel()
		{
			var ids = new List<Guid>
			{
				Guid.NewGuid(),
				Guid.NewGuid(),
			};
			const int threadsToRun = 32;
			var events = new WaitHandle[threadsToRun];
			var exceptions = new List<Exception>();
			for (var i = 0; i < threadsToRun; i++)
			{
				var @event = new ManualResetEvent(false);
				events[i] = @event;
				ThreadPool.QueueUserWorkItem(s =>
				{
					try
					{
						Run(ids);
					}
					catch (Exception ex)
					{
						exceptions.Add(ex);
					}
					finally
					{
						@event.Set();
					}
				});
			}
			WaitHandle.WaitAll(events);
			Assert.IsEmpty(exceptions);
		}
        public void TestThreading()
        {
            try
            {
                var srids = new[] {4326, 31467, 3857, 27700};
                var precisionModels = new[]
                    {
                        new PrecisionModel(PrecisionModels.Floating), 
                        new PrecisionModel(PrecisionModels.FloatingSingle),
                        new PrecisionModel(1),
                        new PrecisionModel(10),
                        new PrecisionModel(100),
                    };

                const int numWorkItems = 30;
                var waitHandles = new WaitHandle[numWorkItems];
                for (var i = 0; i < numWorkItems; i++)
                {
                    waitHandles[i] = new AutoResetEvent(false);
                    ThreadPool.QueueUserWorkItem(TestFacories, new object[] {srids, precisionModels, waitHandles[i], i+1, false});
                }

                WaitHandle.WaitAll(waitHandles);
                Console.WriteLine("\nDone!");
                Assert.LessOrEqual(srids.Length * precisionModels.Length, ((NtsGeometryServices)GeometryServiceProvider.Instance).NumFactories,
                    "Too many factories created!");
                Assert.IsTrue(true);
            }
            catch (Exception)
            {
                Assert.IsTrue(false);
            }

        }
        public static IEnumerable<object[]> SignalAndWait_MemberData()
        {
            var toSignal = new WaitHandle[] { new ManualResetEvent(false), new Mutex(), new Semaphore(1, 1) };
            var toWaitOn = new AutoResetEvent(false);
            var callSignalAndWait =
                new Func<WaitHandle, WaitHandle, bool>[]
                {
                    (s, w) => WaitHandle.SignalAndWait(s, w),
                    (s, w) => WaitHandle.SignalAndWait(s, w, 0, false),
                    (s, w) => WaitHandle.SignalAndWait(s, w, TimeSpan.Zero, false),
                };

            for (int signalIndex = 0; signalIndex < toSignal.Length; ++signalIndex)
            {
                for (int callIndex = 0; callIndex < callSignalAndWait.Length; ++callIndex)
                {
                    var skipInfiniteWaitTests = callIndex == 0;
                    yield return
                        new object[]
                        {
                            toSignal[signalIndex],
                            toWaitOn,
                            callSignalAndWait[callIndex],
                            skipInfiniteWaitTests
                        };
                }
            }
        }
예제 #9
0
파일: Parser.cs 프로젝트: JadeHub/Jade
        private void WorkerThreadLoop()
        {
            WaitHandle[] waitHandles = new WaitHandle[2] { _stopEvent, _workerParseEvent };
            while (true)
            {
                int wait = WaitHandle.WaitAny(waitHandles);
                if (wait == 0)
                    return;

                //Drain the work queue
                while (true)
                {
                    ParseJob job = null;
                    lock (_lock)
                    {
                        if (_work.Count > 0)
                        {
                            job = _work.First();
                            _work.RemoveAt(0);
                        }
                        else
                        {
                            break;
                        }
                    }
                    Parse(job);
                }
            }
        }
예제 #10
0
        /// <summary>
        /// Waits until one of the tasks represented by <see cref="taskHandles"/> is finished, all remaining task will be aborted.
        /// </summary>
        /// <param name="taskHandles">The task handles to wait on.</param>
        /// <returns></returns>
        public static int WaitAny(params ITaskHandle[] taskHandles)
        {
            //FIXME: The is broken, we should return if a scheduled task is finished not ignore it.
            // create wait handle array
            int maxLength = taskHandles.Length;
            var scheduledTasks = new IScheduledTask[maxLength];
            int index = 0;
            for (int i = 0; i < maxLength; i++) {
                var scheduledTask = taskHandles[i] as IScheduledTask;
                if(scheduledTask != null) {
                    if(!scheduledTask.IsFinished) {
                        scheduledTasks[index] = scheduledTask;
                        index++;
                    }
                } else {
                    throw new InvalidOperationException(String.Format("Couldn't convert task handle \"{0}\" to a IScheduledTask.", taskHandles[i]));
                }
            }

            int length = index;
            var waitHandles = new WaitHandle[index];
            for (int i = 0; i < length; i++) {
                waitHandles[i] = scheduledTasks[i].FinishedHandle;
            }
            int releasedIndex = WaitHandle.WaitAny(waitHandles);
            // release resources
            for (int i = 0; i < index; i++) {
                scheduledTasks[i].Close();
            }
            return releasedIndex;
        }
예제 #11
0
        private const int TIMEOUT = 1; // seconds

        public Server()
        {
            tcpClient = new TcpClient();
            try
            {
                IAsyncResult ar = tcpClient.BeginConnect("localhost", 8100, null, null);
                System.Threading.WaitHandle wh = ar.AsyncWaitHandle;
                try
                {
                    if (!ar.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(TIMEOUT), false))
                    {
                        tcpClient.Close();
                        throw new TimeoutException();
                    }

                    tcpClient.EndConnect(ar);
                }
                finally
                {
                    wh.Close();
                }


                // spin off listener to new thread
                Thread clientThread = new Thread(new ParameterizedThreadStart(HandleClientComm));
                clientThread.Start(tcpClient);

                Send("Hello from XNA!");
                SubscribeToGameEvents();
            }
            catch
            {
                Console.WriteLine("Could not connect to TCP server!");
            }
        }
예제 #12
0
파일: Server.cs 프로젝트: jiowchern/Regulus
        /// <summary>
        ///     Initializes a new instance of the <see cref="Server" /> class.
        /// </summary>
        /// <param name="core">
        ///     進入點物件
        /// </param>
        /// <param name="port">
        ///     監聽的埠
        /// </param>
        public Server(ICore core, int port)
        {
            _ThreadCoreHandler = new ThreadCoreHandler(core);
            _ThreadSocketHandler = new ThreadSocketHandler(port, _ThreadCoreHandler);

            _WaitSocket = new AutoResetEvent(false);
        }
예제 #13
0
 public static bool SignalAndWait(WaitHandle toSignal, WaitHandle toWaitOn, int millisecondsTimeout, bool exitContext)
 {
     if ((Environment.OSInfo & Environment.OSName.Win9x) != Environment.OSName.Invalid)
     {
         throw new PlatformNotSupportedException(Environment.GetResourceString("PlatformNotSupported_Win9x"));
     }
     if (toSignal == null)
     {
         throw new ArgumentNullException("toSignal");
     }
     if (toWaitOn == null)
     {
         throw new ArgumentNullException("toWaitOn");
     }
     if (-1 > millisecondsTimeout)
     {
         throw new ArgumentOutOfRangeException("millisecondsTimeout", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1"));
     }
     int num = SignalAndWaitOne(toSignal.safeWaitHandle, toWaitOn.safeWaitHandle, millisecondsTimeout, toWaitOn.hasThreadAffinity, exitContext);
     if ((0x7fffffff != num) && toSignal.hasThreadAffinity)
     {
         Thread.EndCriticalRegion();
         Thread.EndThreadAffinity();
     }
     if (0x80 == num)
     {
         throw new AbandonedMutexException();
     }
     if (0x12a == num)
     {
         throw new InvalidOperationException(Environment.GetResourceString("Threading.WaitHandleTooManyPosts"));
     }
     return (num == 0);
 }
예제 #14
0
	// Validate the contents of a "waitHandles" array and
	// return a new array of low-level handles.
	private static IntPtr[] ValidateHandles(WaitHandle[] waitHandles)
			{
				int posn, posn2;
				WaitHandle handle;
				IntPtr[] lowLevel;
				if(waitHandles == null)
				{
					throw new ArgumentNullException("waitHandles");
				}
				if(waitHandles.Length > 64)
				{
					throw new NotSupportedException
						(_("NotSupp_MaxWaitHandles"));
				}
				lowLevel = new IntPtr [waitHandles.Length];
				for(posn = waitHandles.Length - 1; posn >= 0; --posn)
				{
					if((handle = waitHandles[posn]) == null ||
					   handle.privateData == IntPtr.Zero)
					{
						throw new ArgumentNullException
							("waitHandles[" + posn + "]");
					}
					for(posn2 = posn - 1; posn2 >= 0; --posn2)
					{
						if(handle == waitHandles[posn2])
						{
							throw new DuplicateWaitObjectException();
						}
					}
					lowLevel[posn] = handle.privateData;
				}
				return lowLevel;
			}
예제 #15
0
파일: CanWait.cs 프로젝트: jzabroski/mm
        protected bool WaitAny(int millisecondsTimeout, params System.Threading.WaitHandle[] handles)
        {
            // We are basically just calling System.Threading.WaitHandle.WaitAny on the handle(s) provided,
            // but we also include the example's _stopHandle in the list of handles;  this is an event that
            // gets fired when the user clicks the "Stop" button, allowing us to have a more responsive GUI.
            // In a command-line version of the same example, you would leave that part out.

            System.Threading.WaitHandle[] ar = new System.Threading.WaitHandle[handles.Length + 1];
            ar[0] = _stopEvent;
            for (int i = 0; i < handles.Length; i++)
            {
                ar[i + 1] = handles[i];
            }

            int n = System.Threading.WaitHandle.WaitAny(ar, millisecondsTimeout);

            if (n == System.Threading.WaitHandle.WaitTimeout)
            {
                WriteLine("TIMED OUT WAITING FOR A RESPONSE");
                return(false);
            }
            if (n == 0)
            {
                WriteLine("CANCELLED BY USER");
                return(false);
            }
            return(true);
        }
예제 #16
0
        public int Start(out string strError)
        {
            strError = "";

            Debug.Assert(_thread == null, "");
            _thread = new Thread(new ThreadStart(ThreadMethod));
            _thread.Start();

            // 等待,直到完全启动
            WaitHandle[] events = new WaitHandle[2];

            events[0] = _eventClosed;
            events[1] = _eventStarted;
            int index = WaitHandle.WaitAny(events, -1, false);
#if NO
            if (index == WaitHandle.WaitTimeout)
                return;
            if (index == 0)
                return;
#endif
            if (string.IsNullOrEmpty(this.ErrorInfo) == false)
            {
                strError = this.ErrorInfo;
                return -1;
            }

            return 0;
        }
예제 #17
0
        public CCanAppli()
        {
            // Initialisation du CAN.
            UInt32 bitRate = (UInt32)((8 - 1) << 20) | (UInt32)((15 - 1) << 16) | (UInt32)((12 - 1) << 0);    //Channel1
            m_busCan = new CAN(CAN.Channel.Channel_1, bitRate, 100);

            //
            m_tabWaitDONE = new WaitHandle[]
            {
                new AutoResetEvent(false),
                new AutoResetEvent(false),
                new AutoResetEvent(false)
            };
            m_waitACK = new AutoResetEvent(false);

            // Tableau de data reçu.
            m_dataRecus[0] = new CAN.Message();

            // Initialisation de l'evenement permetant de detecter une erreur CAN.
            m_busCan.ErrorReceivedEvent += new CANErrorReceivedEventHandler(m_busCan_ErrorReceivedEvent);

            // Initialisation de l'evenement permetant de detecter une reponse.
            m_busCan.DataReceivedEvent += new CANDataReceivedEventHandler(m_busCan_DataReceivedEvent);

            mutex = new Object();
        }
        static void Main()
        {
            const int taskCount = 4;

            var mEvents = new ManualResetEventSlim[taskCount];
            var waitHandles = new WaitHandle[taskCount];
            var calcs = new Calculator[taskCount];

            for (int i = 0; i < taskCount; i++)
            {
                int i1 = i;
                mEvents[i] = new ManualResetEventSlim(false);
                waitHandles[i] = mEvents[i].WaitHandle;
                calcs[i] = new Calculator(mEvents[i]);
                Task.Run(() => calcs[i1].Calculation(i1 + 1, i1 + 3));
            }

            for (int i = 0; i < taskCount; i++)
            {
                //   int index = WaitHandle.WaitAny(mEvents.Select(e => e.WaitHandle).ToArray());
                int index = WaitHandle.WaitAny(waitHandles);
                if (index == WaitHandle.WaitTimeout)
                {
                    WriteLine("Timeout!!");
                }
                else
                {
                    mEvents[index].Reset();
                    WriteLine($"finished task for {index}, result: {calcs[index].Result}");
                }
            }


        }
예제 #19
0
        public DialogResult ShowDialog(MobileRemoteUI parentForm, WaitHandle waitResult, AddressSelector.BluetoothDevice device, BluetoothHidWriter hidWriter)
        {
            _statusLabel.Text = "Connecting...";
            _hidWriter = hidWriter;
            _waitResult = waitResult;
            if (device.Address > 0)
            {
                _existingMachine.Dock = DockStyle.Fill;
                _existingMachine.Visible = true;
                _newMachineLabel.Visible = false;
            }
            else
            {
                _newMachineLabel.Dock = DockStyle.Fill;
                _newMachineLabel.Visible = true;
                _existingMachine.Visible = false;
            }

            timer1.Enabled = true;

            if (waitResult.WaitOne(1000, false))
            {
                //return DialogResult.OK;
            }

            try
            {
                return base.ShowDialog(parentForm);
            }
            finally
            {
                timer1.Enabled = false;
            }
        }
예제 #20
0
파일: Program.cs 프로젝트: Rugut/UPP
 private static void Ждать(WaitHandle[] waitHandle)
 {
     if (waitHandle.Length == 0)
     {
         return;
     }
     else if (waitHandle.Length <= 64)
     {
         WaitHandle.WaitAll(waitHandle);
         return;
     }
     var waitHandles = new WaitHandle[64];
     for (var sourceIndex = 0; sourceIndex < waitHandle.Length; sourceIndex += 64)
     {
         if (waitHandle.Length - sourceIndex < 64)
         {
             Array.Resize(ref waitHandles, waitHandle.Length - sourceIndex);
             Array.Copy(waitHandle, sourceIndex, waitHandles, 0, waitHandle.Length - sourceIndex);
         }
         else
         {
             Array.Copy(waitHandle, sourceIndex, waitHandles, 0, 64);
         }
         WaitHandle.WaitAll(waitHandles);
     }
 }
예제 #21
0
파일: WaitHandle.cs 프로젝트: runefs/Marvin
		static void CheckArray (WaitHandle [] handles, bool waitAll)
		{
			if (handles == null)
				throw new ArgumentNullException ("waitHandles");

			int length = handles.Length;
			if (length > 64)
				throw new NotSupportedException ("Too many handles");

#if false
			//
			// Although we should thrown an exception if this is an STA thread,
			// Mono does not know anything about STA threads, and just makes
			// things like Paint.NET not even possible to work.
			//
			// See bug #78455 for the bug this is supposed to fix. 
			// 
			if (waitAll && length > 1 && IsSTAThread)
				throw new NotSupportedException ("WaitAll for multiple handles is not allowed on an STA thread.");
#endif
			foreach (WaitHandle w in handles) {
				if (w == null)
					throw new ArgumentNullException ("waitHandles", "null handle");

#if NET_2_0
				if (w.safe_wait_handle == null)
					throw new ArgumentException ("null element found", "waitHandle");
#else
				if (w.os_handle == InvalidHandle)
					throw new ArgumentException ("null element found", "waitHandle");
#endif
			}
		}
예제 #22
0
 public void Start()
 {
     _cancellation = new CancellationTokenSource();
     _cancellationToken = _cancellation.Token;
     _cancel = _cancellationToken.WaitHandle;
     Task.Factory.StartNew(StartListener, _cancellationToken);
 }
예제 #23
0
파일: Program.cs 프로젝트: vnkolt/NetOffice
        private static void DoTest()
        {
            _application = new Excel.Application();
            Excel.Workbook book = _application.Workbooks.Add();

            WaitHandle[] waitHandles = new WaitHandle[3];

            Thread thread1 = new Thread(new ParameterizedThreadStart(Thread1Method));
            Thread thread2 = new Thread(new ParameterizedThreadStart(Thread2Method));
            Thread thread3 = new Thread(new ParameterizedThreadStart(Thread3Method));

            ManualResetEvent mre1 = new ManualResetEvent(false);
            ManualResetEvent mre2 = new ManualResetEvent(false);
            ManualResetEvent mre3 = new ManualResetEvent(false);

            waitHandles[0] = mre1;
            waitHandles[1] = mre2;
            waitHandles[2] = mre3;

            thread1.Start(mre1);
            thread2.Start(mre2);
            thread3.Start(mre3);

            WaitHandle.WaitAll(waitHandles);

            _application.Quit();
            _application.Dispose();
        }
예제 #24
0
        /// <summary>
        /// Enumerates all top level windows on desktop. WARNING: The method returns null if operation timeout is reached.
        /// </summary>
        /// <param name="milliSecondsTimeout">a timeout for the operation. when a desktop is busy or non responding these method freeze. you can handle this with the operation timeout</param>
        /// <returns>Result Array or null</returns>
        public IntPtr[] EnumerateWindows(int milliSecondsTimeout)
        {
            try
            {
                lock (_lockInstance)
                {
                    Result.Clear();
                    _currentInstance = this;
                    Thread thread1 = new Thread(new ParameterizedThreadStart(EnumerateWindowsAsync));
                    WaitHandle[] waitHandles = new WaitHandle[1];
                    ManualResetEvent mre1 = new ManualResetEvent(false);
                    waitHandles[0] = mre1;
                    thread1.Start(mre1);
                    bool result = WaitHandle.WaitAll(waitHandles, milliSecondsTimeout);
                    if (!result)
                    {
                        thread1.Abort();
                        Result.Clear();
                        _currentInstance = null;
                        return null;
                    }
                    else
                    {
                        _currentInstance = null;
                    }

                }
                return Result.ToArray();
            }
            catch (Exception exception)
            {
                DebugConsole.Default.WriteException(exception);
                throw;
            }
        }
예제 #25
0
		internal RegisteredWaitHandle (WaitHandle waitObject, WaitOrTimerCallback callback, 
												 object cbState, int timeout, bool executeOnlyOnce)
		{
			this.waitObject = waitObject;
			this.callback = callback;
			this.cbState = cbState;
			this.timeout = timeout;
         this.executeOnlyOnce = executeOnlyOnce;

			StWaitable waitable;
			if ((waitable = waitObject.waitable) == null) {

				/*
				 * Either we're dealing with a disposed wait handle
				 * or with some other derived class.
				 */
 
				UnparkCallback (StParkStatus.Inflated);
				return;
			}

			cbparker = new CbParker (UnparkCallback, false, true);
			int ignored = 0;
         waitBlock = waitable._WaitAnyPrologue (cbparker, StParkStatus.Success, ref hint, ref ignored);

			state = ACTIVE;
         int ws = cbparker.EnableCallback (timeout);
         if (ws != StParkStatus.Pending) {
				UnparkCallback (ws);
	      }
		}
예제 #26
0
        /// <summary>
        /// Functionally the same as WaitOne(), but pumps com messa
        /// </summary>
        /// <param name="handle"></param>
        public static void HackyComWaitOne(WaitHandle handle)
        {
            uint nativeResult; // result of the native wait API (WaitForMultipleObjects or MsgWaitForMultipleObjectsEx)
            int managedResult; // result to return from WaitHelper

            IntPtr[] waitHandles = new IntPtr[]{
                handle.SafeWaitHandle.DangerousGetHandle() };
            uint count = 1;

            uint QS_MASK = NativeMethods.QS_ALLINPUT; // message queue status
            QS_MASK = 0; //bizhawk edit?? did we need any messages here?? apparently not???

            // the core loop
            var msg = new NativeMethods.MSG();
            while (true)
            {
                // MsgWaitForMultipleObjectsEx with MWMO_INPUTAVAILABLE returns,
                // even if there's a message already seen but not removed in the message queue
                nativeResult = NativeMethods.MsgWaitForMultipleObjectsEx(
                        count, waitHandles,
                        (uint)0xFFFFFFFF,
                        QS_MASK,
                        NativeMethods.MWMO_INPUTAVAILABLE);

                if (IsNativeWaitSuccessful(count, nativeResult, out managedResult) || WaitHandle.WaitTimeout == managedResult)
                    break;
                // there is a message, pump and dispatch it
                if (NativeMethods.PeekMessage(out msg, IntPtr.Zero, 0, 0, NativeMethods.PM_REMOVE))
                {
                    NativeMethods.TranslateMessage(ref msg);
                    NativeMethods.DispatchMessage(ref msg);
                }
            }
            //m64pFrameComplete.WaitOne();
        }
예제 #27
0
        public void trySocket(string ip, int port, int timeout)
        {
            //Create socket connection
            try {
                //TcpClient client = new TcpClient(ip, port);
                using (TcpClient tcp = new TcpClient())
                {
                    IAsyncResult ar = tcp.BeginConnect(ip, port, null, null);
                    System.Threading.WaitHandle wh = ar.AsyncWaitHandle;
                    try
                    {
                        if (!ar.AsyncWaitHandle.WaitOne(timeout, false))
                        {
                            tcp.Close();
                            throw new TimeoutException();
                        }

                        tcp.EndConnect(ar);
                    }
                    finally
                    {
                        wh.Close();
                    }
                }
                Console.Out.WriteLine(ip + "\t" + port + "\tS");
            } catch (Exception e) {
                if (!openonly)
                {
                    Console.Out.WriteLine(ip + "\t" + port + "\tF\t" + e.Message);
                }
            }
        }
예제 #28
0
        public static bool WaitAll(WaitHandle[] waitHandles, int timeOutMs)
        {
            // throws an exception if there are no wait handles
            if (waitHandles == null)
                throw new ArgumentNullException(nameof(waitHandles));
            if (waitHandles.Length == 0)
                return true;

#if NETSTANDARD1_3
            return WaitHandle.WaitAll(waitHandles, timeOutMs);
#else
            if (Thread.CurrentThread.GetApartmentState() == ApartmentState.STA)
            {
                // WaitAll for multiple handles on an STA thread is not supported.
                // CurrentThread is ApartmentState.STA when run under unit tests
                var successfullyComplete = true;
                foreach (var waitHandle in waitHandles)
                {
                    successfullyComplete = successfullyComplete
                        && waitHandle.WaitOne(timeOutMs, false);
                }
                return successfullyComplete;
            }

            return WaitHandle.WaitAll(waitHandles, timeOutMs, false);
#endif
        }
예제 #29
0
 public bool PingHost(string IP, int Port)
 {
     try
     {
         IPEndPoint   ip                = new IPEndPoint(IPAddress.Parse(IP), Port);
         TcpClient    server            = new TcpClient();
         IAsyncResult ar                = server.BeginConnect(IP, Port, null, null);
         System.Threading.WaitHandle wh = ar.AsyncWaitHandle;
         try
         {
             if (!ar.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(5), false))
             {
                 server.Close();
                 return(false);
             }
             server.EndConnect(ar);
             return(true);
         }
         finally
         {
             wh.Close();
         }
     }
     catch (SocketException)
     {
         return(false);
     }
 }
예제 #30
0
        public void MultiThreadTest()
        {
            var ai = new TwitterApiInfo
            {
                ConsumerKey = "hYd5c8gYxhy3T2Nvj8wLA",
                ConsumerSecret = "KZGPvAN6kgioWlf0zrGYOzKevLatexuuuJlIhJQg"
            };

            var provider = new TwitterDataProvider(ai);

            var messages = provider.GetUserTweets(40648902, null, 10);
            //List<Message> messages = provider.GetUserHomeTimeLine(10);

            Action dlgFirstThread = StartFirstThread;
            Action dlgSecondThread = StartSecondThread;

            var arFirstThread = dlgFirstThread.BeginInvoke(null, null);
            var arSecondThread = dlgSecondThread.BeginInvoke(null, null);

            var waitHandles = new WaitHandle[] { arFirstThread.AsyncWaitHandle, arSecondThread.AsyncWaitHandle };
            //WaitHandle[] waitHandles = new WaitHandle[] { arFirstThread.AsyncWaitHandle };

            WaitHandle.WaitAll(waitHandles);

            Console.WriteLine("Operation complete. Press any key to close window...");
            Console.ReadLine();
        }
 public StreamAsyncResult(SocketAsyncEventArgs e, AsyncCallback callback, System.Threading.WaitHandle waitHandle)
 {
     SocketAsyncEventArgs = e;
     e.UserToken          = this;
     Callback             = callback;
     AsyncWaitHandle      = waitHandle;
 }
예제 #32
0
        protected override void EndProcessing()
        {
            WaitHandle[] waitHandles = new WaitHandle[pendingResults.Count];
            for (int i = 0; i < waitHandles.Length; i++)
            {
                waitHandles[i] = pendingResults[i].AsyncWaitHandle;
            }

            WaitHandle.WaitAll(waitHandles);

            for (int i = 0; i < pendingResults.Count; i++)
            {
                try
                {
                    WriteObject(Dns.EndGetHostEntry(pendingResults[i]));
                }
                catch (PipelineStoppedException)
                {
                    throw;
                }
                catch (Exception exc)
                {
                    ErrorHandler.WriteGetHostEntryError(pendingResults[i].AsyncState.ToString(), exc);
                }
            }

            base.EndProcessing();
        }
예제 #33
0
		internal void Wait (object state)
		{
			bool release = false;
			try {
				_waitObject.SafeWaitHandle.DangerousAddRef (ref release);
				try {
					WaitHandle[] waits = new WaitHandle[] {_waitObject, _cancelEvent};
					do {
						int signal = WaitHandle.WaitAny (waits, _timeout, false);
						if (!_unregistered) {
							lock (this) {
								_callsInProcess++;
							}
							ThreadPool.QueueUserWorkItem (new WaitCallback (DoCallBack), (signal == WaitHandle.WaitTimeout));
						}
					} while (!_unregistered && !_executeOnlyOnce);
				} catch {
				}

				lock (this) {
					_unregistered = true;
					if (_callsInProcess == 0 && _finalEvent != null)
						NativeEventCalls.SetEvent (_finalEvent.SafeWaitHandle);
				}
			} catch (ObjectDisposedException) {
				// Can happen if we called Unregister before we had time to execute Wait
				if (release)
					throw;
			} finally {
				if (release)
					_waitObject.SafeWaitHandle.DangerousRelease ();
			}
		}
예제 #34
0
    public bool ClientConnect()
    {
        try
        {
            // 建立 Client
            tcpClient = new TcpClient();

            // 測試連線是否存在 TimeOut 2 Second
            IAsyncResult result = tcpClient.BeginConnect(serverIP, serverPort, null, null);
            System.Threading.WaitHandle handler = result.AsyncWaitHandle;

            if (!result.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(2), false))
            {
                tcpClient.Close();
                tcpClient.EndConnect(result);
                handler.Close();
                throw new TimeoutException();
            }

            // 連線至 Server
            tcpClient.Connect(serverIP, serverPort);
            clientSocket = tcpClient.Client;

            Debug.Log("連線成功");

            return(true);
        }
        catch
        {
            Debug.Log("連線失敗");
            return(false);
        }
    }
예제 #35
0
        static WaitHandle StartOnMySignal(WaitHandle signalWhenReadyToStart, Action callback)
        {
            var exitHandle = new ManualResetEvent(false);

            ThreadPool.QueueUserWorkItem(delegate
            {
                signalWhenReadyToStart.WaitOne();

                try
                {
                    var watch = Stopwatch.StartNew();

                    while (watch.Elapsed < maxExecutionTime)
                    {
                        callback();
                    }
                }
                catch (Exception ex)
                {
                    exceptions.Add(ex);
                }
                finally
                {
                    exitHandle.Set();
                }
            });

            return exitHandle;
        }
예제 #36
0
        /// <summary>
        /// Runs the bundle with the provided command-line.
        /// </summary>
        /// <param name="commandLine">Optional command-line to pass to the bundle.</param>
        /// <returns>Exit code from the bundle.</returns>
        public int Run(string commandLine = null)
        {
            WaitHandle[] waits = new WaitHandle[] { new ManualResetEvent(false), new ManualResetEvent(false) };
            int returnCode = 0;
            int pid = Process.GetCurrentProcess().Id;
            string pipeName = String.Concat("bpe_", pid);
            string pipeSecret = Guid.NewGuid().ToString("N");

            using (NamedPipeServerStream pipe = new NamedPipeServerStream(pipeName, PipeDirection.InOut, 1))
            {
                using (Process bundleProcess = new Process())
                {
                    bundleProcess.StartInfo.FileName = this.Path;
                    bundleProcess.StartInfo.Arguments = String.Format("{0} -burn.embedded {1} {2} {3}", commandLine ?? String.Empty, pipeName, pipeSecret, pid);
                    bundleProcess.StartInfo.UseShellExecute = false;
                    bundleProcess.StartInfo.CreateNoWindow = true;
                    bundleProcess.Start();

                    Connect(pipe, pipeSecret, pid, bundleProcess.Id);

                    PumpMessages(pipe);

                    bundleProcess.WaitForExit();
                    returnCode = bundleProcess.ExitCode;
                }
            }

            return returnCode;
        }
예제 #37
0
        protected bool WaitAny(int millisecondsTimeout, params System.Threading.WaitHandle[] handles)
        {
            // We are basically just calling System.Threading.WaitHandle.WaitAny on the handle(s) provided,
              // but we also include the example's _stopHandle in the list of handles;  this is an event that
              // gets fired when the user clicks the "Stop" button, allowing us to have a more responsive GUI.
              // In a command-line version of the same example, you would leave that part out.

              System.Threading.WaitHandle[] ar = new System.Threading.WaitHandle[handles.Length + 1];
              ar[0] = _stopEvent;
              for (int i = 0; i < handles.Length; i++)
            ar[i + 1] = handles[i];

              int n = System.Threading.WaitHandle.WaitAny(ar, millisecondsTimeout);
              if (n == System.Threading.WaitHandle.WaitTimeout)
            {
              WriteLine("TIMED OUT WAITING FOR A RESPONSE");
              return false;
            }
              if (n == 0)
            {
              WriteLine("CANCELLED BY USER");
              return false;
            }
              return true;
        }
 public void Setup(object asyncState, WaitHandle waitHandle,AsyncCallback callback)
 {
     _asyncState = asyncState;
     _waitHandle = waitHandle;
     _callBack = callback;
     _aborted = false;
 }
예제 #39
0
파일: MainForm.cs 프로젝트: jnnrz/redialer
 private void checkNoBytesTimer_Tick(object sender, EventArgs e)
 {
     if (chkNoBytes.Checked == true)
     {
         RasConnection r = RasConnection.GetActiveConnectionByName(detectedList.Items[detectedList.SelectedIndex].ToString(), RasPhoneBook.GetPhoneBookPath(RasPhoneBookType.User));
         if (r != null)
         {
             using (TcpClient tcp = new TcpClient())
             {
                 IAsyncResult ar = tcp.BeginConnect("google.com", 80, null, null);
                 System.Threading.WaitHandle wh = ar.AsyncWaitHandle;
                 try
                 {
                     if (!ar.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(5), false))
                     {
                         tcp.Close();
                         appendLog("No Bytes. Disconnecting...");
                         r.HangUp();
                     }
                 }
                 finally
                 {
                     wh.Close();
                 }
             }
         }
     }
 }
예제 #40
0
파일: ByteBuffer.cs 프로젝트: quangfox/Voip
        /// <summary>
        /// Waits for the number of elements in the buffer to reach a certain size, or until the timeout is reached or the other wait handle is signaled
        /// </summary>
        /// <param name="nSizeInBuffer"></param>
        /// <param name="nTimeout"></param>
        /// <param name="otherhandletowaiton"></param>
        /// <returns></returns>
        public bool WaitForSize(int nSizeInBuffer, int nTimeout, System.Threading.WaitHandle otherhandletowaiton)
        {
            lock (BufferLock)
            {
                if (m_nSize >= nSizeInBuffer)
                {
                    return(true);
                }
                SizeEvent.Reset();
            }

            TimeSpan tsElapsed;
            DateTime dtStart = DateTime.Now;

            WaitHandle[] handles = new WaitHandle[] { SizeEvent, otherhandletowaiton };
            if (otherhandletowaiton == null)
            {
                handles = new WaitHandle[] { SizeEvent }
            }
            ;
            do
            {
                int nWait = WaitHandle.WaitAny(handles, nTimeout);
                if (nWait == 1)
                {
                    return(false);
                }
                else if (nWait == 0)
                {
                    lock (BufferLock)
                    {
                        SizeEvent.Reset();
                        if (m_nSize >= nSizeInBuffer)
                        {
                            return(true);
                        }
                    }
                }
                else
                {
                    return(false);
                }

                tsElapsed = DateTime.Now - dtStart;
                if (nTimeout != Timeout.Infinite)
                {
                    nTimeout = (int)tsElapsed.TotalMilliseconds;
                    if (nTimeout <= 0)
                    {
                        break;
                    }
                }
            }while (true);

            return(false);
        }

        AutoResetEvent SizeEvent = new AutoResetEvent(false);
        object BufferLock        = new object();
예제 #41
0
        public bool ConnectToTCPServerTestMessage(string ip, int port)
        {
            //this is test code
            bool b = false;

            using (TcpClient tcp = new TcpClient())
            {
                IAsyncResult ar = tcp.BeginConnect("10.10.10.7", 80, null, null);
                System.Threading.WaitHandle wh = ar.AsyncWaitHandle;
                try
                {
                    if (!ar.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(5), false))
                    {
                        tcp.Close();
                        b = false;
                    }
                    else
                    {
                        b = true;
                        tcp.EndConnect(ar);
                    }
                }
                finally
                {
                    wh.Close();
                }
            }

            return(b);


            try
            {
                System.Console.WriteLine("testing network");

                //find a port that works 6000-61000
                //"10.10.10.7", 80
                tc = new TcpClient(ip, port);
                ns = tc.GetStream();
                sw = new StreamWriter(ns);
                //sr = new StreamReader();

                //send data to pc
                sw.WriteLine("hello\r\n");
                sw.Flush();

                //sr.Close();
                sw.Close();
                ns.Close();
                tc.Close();
            }
            catch (Exception ee)
            {
                System.Console.WriteLine("Exception testing network:" + ee.Message);
                return(false);
            }
            System.Console.WriteLine("testing network completed");
            return(true);
        }
        /// <summary>
        /// send data to remote host dequeueing send_queue
        /// send event_Socket_Data_Send_Completed
        /// </summary>
        private void my_send()
        {
            try
            {
                byte[] buffer;
                System.Threading.WaitHandle[] wait_handles = new System.Threading.WaitHandle[2];
                wait_handles[0] = this.evt_close;
                wait_handles[1] = this.evt_more_data_to_send;
                int res_wait;

                for (;;)
                {
                    res_wait = System.Threading.WaitHandle.WaitAny(wait_handles, TIMEOUT_SEND, true);
                    switch (res_wait)
                    {
                    case 0:
                    case System.Threading.WaitHandle.WaitTimeout:
                        this.b_start_send_thread = true;
                        // exit thread
                        return;
                    }
                    this.evt_more_data_to_send.Reset();
                    while (send_queue.Count > 0)  // while there's data to send
                    {
                        // dequeue data of send_queue
                        this.evt_unlocked_send_queue.WaitOne();
                        buffer = (byte[])send_queue.Dequeue();
                        this.evt_unlocked_send_queue.Set();

                        this.data_socket.SendTo(buffer, 0, buffer.Length, System.Net.Sockets.SocketFlags.DontRoute, remote_ep);

                        if (this.event_Socket_Data_Send_Completed != null)
                        {
                            this.event_Socket_Data_Send_Completed(this, new EventArgs());
                        }
                    }
                }
            }
            catch (Exception e)
            {
                if (this.event_Socket_Data_Error != null)
                {
                    this.event_Socket_Data_Error(this, new EventArgs_Exception(e));
                }
                // clear send queue
                this.evt_unlocked_send_queue.WaitOne();
                this.send_queue.Clear();
                this.evt_unlocked_send_queue.Set();
                // restart thread to send data
                ThreadStart myThreadStart = new ThreadStart(this.my_send);
                Thread      myThread      = new Thread(myThreadStart);
                myThread.Start();
            }
        }
예제 #43
0
        async Task <bool> WaitOnHandle(System.Threading.WaitHandle waitHandle)
        {
            var threadID = m_IThreading.GetCurrentThreadID().ToString();

            System.Diagnostics.Debug.WriteLine(threadID + "WaitOnHandle");
            bool bRecieved = waitHandleForDownloadToEnd.WaitOne(TimeSpan.FromMilliseconds(30000));

            threadID = m_IThreading.GetCurrentThreadID().ToString();
            System.Diagnostics.Debug.WriteLine(threadID + "WaitOnHandle Finished");
            return(bRecieved);
        }
        /// <summary>
        /// send data to remote host dequeueing send_queue
        /// send event_Socket_Data_Send_Completed
        /// </summary>
        private void my_send()
        {
            udp_send_object obj_send = null;

            try
            {
                byte[] buffer;
                System.Threading.WaitHandle[] wait_handles = new System.Threading.WaitHandle[2];
                wait_handles[0] = this.evt_close;
                wait_handles[1] = this.evt_more_data_to_send;
                int res_wait;

                for (;;)
                {
                    res_wait = System.Threading.WaitHandle.WaitAny(wait_handles);
                    if (res_wait == 0)
                    {
                        // exit thread
                        return;
                    }
                    this.evt_more_data_to_send.Reset();
                    while (send_queue.Count > 0) // while there's data to send
                    {
                        // dequeue data of send_queue
                        this.evt_unlocked_send_queue.WaitOne();
                        obj_send = (udp_send_object)send_queue.Dequeue();
                        this.evt_unlocked_send_queue.Set();
                        buffer = obj_send.buffer;
                        this.srvsocket.SendTo(buffer, 0, buffer.Length, SocketFlags.None, obj_send.remote_endpoint);
                        if (this.event_Socket_Server_Send_Completed != null)
                        {
                            this.event_Socket_Server_Send_Completed(this, new EventArgs_EndPoint(obj_send.remote_endpoint));
                        }
                    }
                }
            }
            catch (Exception e)
            {
                if (event_Socket_Server_Error != null)
                {
                    event_Socket_Server_Error(this, new EventArgs_Exception(e));
                }

                // clear send queue
                this.evt_unlocked_send_queue.WaitOne();
                this.send_queue.Clear();
                this.evt_unlocked_send_queue.Set();
                // restart thread to send data
                ThreadStart myThreadStart = new ThreadStart(this.my_send);
                Thread      myThread      = new Thread(myThreadStart);
                myThread.Start();
            }
        }
예제 #45
0
        }//ConnectToServer()

        //
        //
        //
        //
        //
        // ****				Try Connect To Client()					****
        //
        private bool TryConnectToClient(IPEndPoint ip, out TcpClient client)
        {
            client = null;
            bool isSuccess = false;

            TcpClient tcpClient = null;

            System.Threading.WaitHandle waitHandle = null;
            try
            {
                tcpClient = new TcpClient();
                IAsyncResult async = tcpClient.BeginConnect(ip.Address, ip.Port, null, null);
                waitHandle = async.AsyncWaitHandle;

                if (!async.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(m_ConnectTimeout), false))
                {
                    tcpClient.Close();
                    isSuccess = false;
                }
                else
                {
                    tcpClient.EndConnect(async);
                    client    = tcpClient;
                    isSuccess = true;
                }
            }
            catch (Exception ex)
            {
                if (tcpClient != null)
                {
                    tcpClient.Close();
                }
                OnInternalMessage(string.Format("TryConnectToClient exception: {0}.", ex.Message));
                isSuccess = false;
            }
            finally
            {
                if (waitHandle != null)
                {
                    waitHandle.Close();
                }
            }

            // Exit.
            return(isSuccess);
        }        //TryConnectToClient()
예제 #46
0
        private void ThreadProc()
        {
            System.Threading.WaitHandle[] handles = new System.Threading.WaitHandle[] { m_ExitEvent, m_TriggerEvent };
            int handleIndex;

            try
            {
                while (true)
                {
                    handleIndex = System.Threading.WaitHandle.WaitAny(handles);
                    if (handleIndex == 0)
                    {
                        return;                 //Exit() was called
                    }
                    try
                    {
                        while (m_queue.Count > 0)
                        {
                            object[] objs = (object[])m_queue.Dequeue();
                            if (m_func(objs) == false)
                            {
                                Exit();
                            }
                        }
                    }
                    catch (Exception e) //never allow an m_func() exception terminate this thread.
                    {
                        //synchronous Log uses Async class so we can't use it here
                        DBG.WriteLine("Thread: {0}\r\n{1}", (m_Thread.Name == null?"<unknown>":m_Thread.Name), e);
                    }
                }
            }
            finally
            {
                if (m_ExitEvent != null)
                {
                    m_ExitEvent.Close(); m_ExitEvent = null;
                }
                if (m_TriggerEvent != null)
                {
                    m_TriggerEvent.Close(); m_TriggerEvent = null;
                }
                m_queue.Clear();
                m_queue = null;
            }
        }
예제 #47
0
        /// <summary>
        /// Connect with timeout
        /// </summary>
        /// <param name="connectTimeout">connect timeout. In millisecond</param>
        public void Connect(int connectTimeout)
        {
            if (connectTimeout > 30000)
            {
                Connect();
                return;
            }

            if (_Client == null)
            {
                _Client = new System.Net.Sockets.TcpClient();
            }

            IPEndPoint serverEndPoint =
                new IPEndPoint(RemoteAddress, Port);

            IAsyncResult ar = _Client.BeginConnect(serverEndPoint.Address,
                                                   serverEndPoint.Port, null, null);

            System.Threading.WaitHandle wh = ar.AsyncWaitHandle;

            try
            {
                if (!ar.AsyncWaitHandle.WaitOne(connectTimeout, false))
                {
                    _Client.Close();
                    throw new TimeoutException(string.Format("Try to connect {0} timeout", serverEndPoint));
                }

                _Client.EndConnect(ar);
            }
            finally
            {
                wh.Close();
            }

            _ClientStream = _Client.GetStream();

            if (_Async)
            {
                _Thread = new Thread(AsyncMessageRecv);
                _Thread.IsBackground = true;
                _Thread.Start();
            }
        }
예제 #48
0
        /// <summary>
        /// Connects to a given IPEndPoint
        /// Doesn't allow failed connections
        /// </summary>
        /// <param name="ipEndPoint"></param>
        /// <returns></returns>
        private static bool ConnectToServerAsync(System.Net.IPEndPoint ipEndPoint)
        {
            m_client = new TcpClient();

            bool connectionSuceeded = false;

            //sets up an asyncronos connection
            IAsyncResult ar = m_client.BeginConnect(ipEndPoint.Address, ipEndPoint.Port, null, null);

            System.Threading.WaitHandle wh = ar.AsyncWaitHandle;
            try
            {
                //blocks the current thread until either timeout is reached or connection is successful
                if (!ar.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(3), false))
                {
                    m_client.Close();
                    System.Diagnostics.Debug.WriteLine("The server is not running");

                    return(connectionSuceeded = false);
                }

                m_client.EndConnect(ar);
            }
            catch (Exception e)
            {
                System.Console.WriteLine(e.Message);
                return(false);
            }
            finally
            {
                wh.Close();
            }

            connectionSuceeded = true;

            // create a thread to handle data received from Server
            Thread HandleDataFromServerThread = new Thread(new ParameterizedThreadStart(HandleDataFromServer));

            HandleDataFromServerThread.Name         = "Handle Data From Server Thread";
            HandleDataFromServerThread.IsBackground = true;
            HandleDataFromServerThread.Start(m_client);

            return(connectionSuceeded);
        }
예제 #49
0
        private bool SendToPrinter(string printerIPAddress, string message)
        {
            //   log.Info("SendToPrinter IP {0} Message {1}",printerIPAddress,message);
            bool sendOK = false;

            try
            {
                using (TcpClient client = new TcpClient())
                {
                    //   log.Info("SendToPrinter BeginConnect IP {0}",printerIPAddress);
                    IAsyncResult ar = client.BeginConnect(printerIPAddress, 9100, null, null);
                    System.Threading.WaitHandle wh = ar.AsyncWaitHandle;
                    if (!ar.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(5), false))
                    {
                        //      log.Error("SendToPrinter BeginConnect Timeout IP {0}",printerIPAddress);
                        client.Close();
                        throw new TimeoutException();
                    }
                    //     log.Info("SendToPrinter BeginConnect Successful IP {0}",printerIPAddress);
                    client.EndConnect(ar);

                    using (NetworkStream ns = client.GetStream())
                    {
                        using (StreamWriter sw = new StreamWriter(ns))
                        {
                            sw.WriteLine(message);
                            sw.Close();
                            sw.Dispose();
                        }
                    }
                    sendOK = true;
                    //  log.Info("SendToPrinter Successful IP {0}",printerIPAddress);
                    client.Close();
                }
                Thread.Sleep(100);
            }
            catch
            {
                sendOK = false;
            }
            return(sendOK);
        }
예제 #50
0
        void wait_for_completion()
        {
again:
            MainLoop loop = main_loop_stack.Peek();

            Report.Debug(DebugFlags.CLI, "{0} waiting for completion", loop);

            ST.WaitHandle[] wait = new ST.WaitHandle[] {
                loop.CompletedEvent, interrupt_event, nested_break_state_event
            };
            int ret = ST.WaitHandle.WaitAny(wait);

            Report.Debug(DebugFlags.CLI, "{0} waiting for completion done: {1}", loop, ret);

            if (loop.Completed)
            {
                main_loop_stack.Pop();
                goto again;
            }
        }
예제 #51
0
        /// <summary>
        /// Executes a parallel for loop using ThreadPool.
        /// </summary>
        /// <param name="i0">The start index (inclusive).</param>
        /// <param name="i1">The end index (exclusive).</param>
        /// <param name="action">The action that is invoked once per iteration.</param>
        private static void ParallelFor(int i0, int i1, Alt.Action <int> action)
        {
            // Environment.ProcessorCount is not available here. Use 4 processors.
            int p = 4;

            // Initialize wait handles
            var doneEvents = new System.Threading.WaitHandle[p];

            for (int i = 0; i < p; i++)
            {
                doneEvents[i] = new System.Threading.ManualResetEvent(false);
            }

            // Invoke the action of a partition of the range
            Alt.Action <int, int, int> invokePartition = (k, j0, j1) =>
            {
                for (int i = j0; i < j1; i++)
                {
                    action(i);
                }

                ((System.Threading.ManualResetEvent)doneEvents[k]).Set();
            };

            // Start p background threads
            int n = (i1 - i0 + p - 1) / p;

            for (int i = 0; i < p; i++)
            {
                int k  = i;
                int j0 = i0 + (i * n);
                var j1 = Math.Min(j0 + n, i1);
                System.Threading.ThreadPool.QueueUserWorkItem(state => invokePartition(k, j0, j1));
            }

            // Wait for the threads to finish
            foreach (var wh in doneEvents)
            {
                wh.WaitOne();
            }
        }
예제 #52
0
        /// <summary>
        /// Check server port for open
        /// </summary>
        /// <param name="address"></param>
        /// <param name="port"></param>
        /// <param name="timeout"> </param>
        /// <returns></returns>
        public static bool IsPortOpened(string address, int port, int timeout = 3)
        {
            var ip = System.Net.Dns.GetHostAddresses(address)[0];

            AutoResetEvent connectDone = new AutoResetEvent(false);
            TcpClient      client      = new TcpClient();


            // connect with timeout
            //  http://stackoverflow.com/questions/795574/c-sharp-how-do-i-stop-a-tcpclient-connect-process-when-im-ready-for-the-progr
            try
            {
                using (TcpClient tcp = new TcpClient())
                {
                    IAsyncResult ar = tcp.BeginConnect(ip, port, null, null);
                    System.Threading.WaitHandle wh = ar.AsyncWaitHandle;
                    try
                    {
                        if (!ar.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(timeout), false))
                        {
                            tcp.Close();
                            throw new TimeoutException();
                        }
                        tcp.EndConnect(ar);
                    }
                    finally
                    {
                        wh.Close();
                    }
                }
            }
            catch (Exception)
            {
                return(false);
            }

            return(true);
        }
예제 #53
0
    public void connect2Server()
    {
        // tries to connect for 2 seconds and then throws an error if it cannot connect
        // taken adapted from https://social.msdn.microsoft.com/Forums/vstudio/en-us/2281199d-cd28-4b5c-95dc-5a888a6da30d/tcpclientconnect-timeout
        client = new TcpClient();
        IAsyncResult ar = client.BeginConnect(ipAddress, port, null, null);

        System.Threading.WaitHandle wh = ar.AsyncWaitHandle;
        try
        {
            if (!ar.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(2), false))
            {
                client.Close();
                throw new TimeoutException();
            }

            client.EndConnect(ar);
        }
        finally
        {
            wh.Close();
        }
        print("SOCKET READY");
    }
예제 #54
0
        public bool ConnectToHost(System.Net.IPAddress address, int port)
        {
            #region TCPClientConnection
            tcpClient = new TcpClient();
            log.Info("Connecting.....");

            IAsyncResult ar = tcpClient.BeginConnect(address, port, null, null);

            System.Threading.WaitHandle wh = ar.AsyncWaitHandle;
            try
            {
                if (!ar.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(5), false))
                {
                    tcpClient.Close();
                    connected = false;
                    log.Error("TCP Connection to " + address + "port " + port.ToString() + " timeout");
                    throw new TimeoutException();
                }

                tcpClient.EndConnect(ar);
                connected = true;
                log.Error("TCP Connection to " + address + "port " + port.ToString() + " completed");
                ipaddresstohost = address;
            }
            catch (Exception ex)
            {
                return(false);
            }
            finally
            {
                wh.Close();
            }
            return(true);

            #endregion
        }//connect to Telnet server
예제 #55
0
 private void setaHandle(ref System.Threading.WaitHandle waitHandleAssincrono)
 {
     m_WaitHandleAssincrono = waitHandleAssincrono;
 }
예제 #56
0
        private void Run()
        {
            TcpClient    tcp = new TcpClient();
            IAsyncResult ar  = tcp.BeginConnect("127.0.0.1", 11000, null, null);

            System.Threading.WaitHandle wh = ar.AsyncWaitHandle;

            if (!ar.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(5), false))
            {
                tcp.Close();
                throw new TimeoutException("Authentication thread timed out.");
            }

            tcp.EndConnect(ar);


            MaybeWait();

            //System.Threading.Thread.Sleep(2000);
            NetworkStream stream = tcp.GetStream();

            byte[] buffer = BitConverter.GetBytes(390458);
            stream.Write(buffer, 0, 4);

            MaybeWait();

            stream.Read(buffer, 0, 4);
            long value = BitConverter.ToInt32(buffer, 0);

            MaybeWait();

            buffer = System.Text.Encoding.UTF8.GetBytes(player.Name);
            stream.Write(BitConverter.GetBytes(buffer.Length), 0, 4);
            MaybeWait();
            stream.Write(buffer, 0, buffer.Length);

            MaybeWait();

            buffer = System.Text.Encoding.UTF8.GetBytes(player.Password);
            //Will always be 128 characters long
            stream.Write(buffer, 0, buffer.Length);

            while (!done)
            {
                float x = player.Position.x + (float)(rand.NextDouble() * 4.0 - 2.0);

                if (x > 800.0f)
                {
                    x = 800.0f;
                }
                else if (x < 0.0f)
                {
                    x = 0.0f;
                }

                float y = player.Position.y + (float)(rand.NextDouble() * 4.0 - 2.0);

                if (y > 600.0f)
                {
                    y = 600.0f;
                }
                else if (y < 0.0f)
                {
                    y = 0.0f;
                }

                player.Position = new Position(x, y);

                stream.Write(BitConverter.GetBytes(player.Position.x), 0, 4);
                MaybeWait();
                stream.Write(BitConverter.GetBytes(player.Position.y), 0, 4);
                MaybeWait();

                buffer = new byte[4];
                stream.Read(buffer, 0, 4);
                int numNearbyPlayers = BitConverter.ToInt32(buffer, 0);
                int numBytes         = numNearbyPlayers * 8;

                MaybeWait();

                buffer = new byte[numBytes];
                stream.Read(buffer, 0, numBytes);

                MaybeWait();

                //float a = BitConverter.ToSingle(buffer, 0);
                //float b = BitConverter.ToSingle(buffer, 4);
            }
        }
예제 #57
0
        public void dataStream(object client_obj)
        {
            //Gecko Connection
            try
            {
                client         = new TcpClient();
                client.NoDelay = true;
                IAsyncResult ar = client.BeginConnect((string)client_obj, 7335, null, null); //Auto Splitter Input Display uses 7335
                System.Threading.WaitHandle wh = ar.AsyncWaitHandle;
                try
                {
                    if (!ar.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(3), false))
                    {
                        client.Close();

                        MessageBox.Show("WiiU: Connection Timeout!", "Warning", MessageBoxButton.OK, MessageBoxImage.Warning);

                        if (ControllerDisconnected != null)
                        {
                            _context.Post((SendOrPostCallback)(_ => ControllerDisconnected(this, EventArgs.Empty)), null);
                        }

                        return;
                    }

                    client.EndConnect(ar);
                }
                finally
                {
                    wh.Close();
                }
            }
            catch (Exception)
            {
                MessageBox.Show("WiiU: Connection Error. Check IP Address!", "Warning", MessageBoxButton.OK, MessageBoxImage.Warning);

                if (ControllerDisconnected != null)
                {
                    _context.Post((SendOrPostCallback)(_ => ControllerDisconnected(this, EventArgs.Empty)), null);
                }

                return;
            }

            //Handle Connection
            stream = client.GetStream();
            EndianBinaryReader reader = new EndianBinaryReader(stream);

            try
            {
                float StickX, StickCX, StickY, StickCY = 0.0f;
                byte  Buttons1, Buttons2, Buttons3 = 0;

                while (true)
                {
                    byte cmd_byte = reader.ReadByte();
                    switch (cmd_byte)
                    {
                    case 0x01:     //Input Data
                    {
                        //1 = 0 bit, 2 = 1 bit, 4 = 2 bit, 8 = 3 bit, 16 = 4 bit, 32 = 5 bit, 64 = 6 bit, 128 = 7 bit

                        //Apply Inputs
                        var outState = new ControllerStateBuilder();

                        StickX = reader.ReadSingle();
                        StickY = reader.ReadSingle();

                        if (StickX <= 1.0f && StickY <= 1.0f && StickX >= -1.0f && StickY >= -1.0f)
                        {
                            outState.SetAnalog("lstick_x", StickX);
                            outState.SetAnalog("lstick_y", StickY);
                        }

                        StickCX = reader.ReadSingle();
                        StickCY = reader.ReadSingle();

                        if (StickCX <= 1.0f && StickCY <= 1.0f && StickCX >= -1.0f && StickCY >= -1.0f)
                        {
                            outState.SetAnalog("cstick_x", StickCX);
                            outState.SetAnalog("cstick_y", StickCY);
                        }

                        Buttons1 = reader.ReadByte();
                        Buttons2 = reader.ReadByte();
                        Buttons3 = reader.ReadByte();

                        outState.SetButton("a", IsBitSet(Buttons1, 7));
                        outState.SetButton("b", IsBitSet(Buttons1, 6));
                        outState.SetButton("x", IsBitSet(Buttons1, 5));
                        outState.SetButton("y", IsBitSet(Buttons1, 4));

                        outState.SetButton("left", IsBitSet(Buttons1, 3));
                        outState.SetButton("right", IsBitSet(Buttons1, 2));
                        outState.SetButton("up", IsBitSet(Buttons1, 1));
                        outState.SetButton("down", IsBitSet(Buttons1, 0));

                        outState.SetButton("zl", IsBitSet(Buttons2, 7));
                        outState.SetButton("zr", IsBitSet(Buttons2, 6));
                        outState.SetButton("l", IsBitSet(Buttons2, 5));
                        outState.SetButton("r", IsBitSet(Buttons2, 4));

                        outState.SetButton("plus", IsBitSet(Buttons2, 3));
                        outState.SetButton("minus", IsBitSet(Buttons2, 2));
                        outState.SetButton("l3", IsBitSet(Buttons2, 1));
                        outState.SetButton("r3", IsBitSet(Buttons2, 0));

                        outState.SetButton("home", IsBitSet(Buttons3, 1));
                        outState.SetButton("touch", IsBitSet(Buttons3, 2));

                        if (ControllerStateChanged != null)
                        {
                            _context.Post((SendOrPostCallback)(_ => ControllerStateChanged(this, outState.Build())), null);
                        }

                        break;
                    }

                    default:
                        throw new Exception("Invalid data");
                    }
                }
            }
            catch (ThreadAbortException)
            {
            }
            catch (Exception)
            {
                if (ControllerDisconnected != null)
                {
                    _context.Post((SendOrPostCallback)(_ => ControllerDisconnected(this, EventArgs.Empty)), null);
                }
            }
        }
예제 #58
0
        /// <summary>
        /// send data to remote host dequeueing send_queue
        /// send event_Socket_Data_Send_Progress
        /// send event_Socket_Data_Send_Completed
        /// </summary>
        private void my_send()
        {
            try
            {
                byte[] local_buffer;
                int    bufsize;
                int    nbbytesent;
                int    nbbyteremaining;
                int    data_send_size;
                int    cpt;
                bool   b_send_sent_completed = true;
                System.Threading.WaitHandle[] wait_handles = new System.Threading.WaitHandle[2];
                wait_handles[0] = this.evt_close;
                wait_handles[1] = this.evt_more_data_to_send;

                int res_wait;

                for (;;)
                {
                    res_wait = System.Threading.WaitHandle.WaitAny(wait_handles);
                    if (res_wait == 0)
                    {
                        // exit thread
                        return;
                    }
                    this.evt_more_data_to_send.Reset();
                    while (this.send_queue.Count > 0) // while there's data to send
                    {
                        // dequeue data of send_queue
                        this.evt_unlocked_send_queue.WaitOne();
                        local_buffer = (byte[])this.send_queue.Dequeue();
                        this.evt_unlocked_send_queue.Set();
                        bufsize         = local_buffer.Length;
                        nbbytesent      = 0;
                        nbbyteremaining = bufsize;
                        data_send_size  = 0;
                        cpt             = 0;
                        //data_send_size=datasocket.Send(local_buffer); // changed to control the amount of data sent
                        while (nbbyteremaining > buffer_size)
                        {
                            if (this.b_cancel_send)
                            {
                                this.evt_unlocked_send_queue.WaitOne();
                                this.send_queue.Clear();
                                this.evt_unlocked_send_queue.Set();

                                this.b_cancel_send    = false;
                                nbbyteremaining       = 0;
                                b_send_sent_completed = false;
                                break;
                            }
                            if (this.locally_closed)
                            {
                                return;
                            }
                            if (!this.datasocket.Connected)
                            {
                                return;
                            }
                            // send a buffer with length=buffer_size
                            data_send_size   = datasocket.Send(local_buffer, cpt * buffer_size, buffer_size, SocketFlags.None);
                            nbbytesent      += data_send_size;
                            nbbyteremaining -= data_send_size;
                            cpt++;
                            //event send progress
                            if (this.event_Socket_Data_Send_Progress != null)
                            {
                                this.event_Socket_Data_Send_Progress(this, new EventArgs_Send_Progress_Socket_Data(nbbytesent, nbbyteremaining, bufsize));
                            }
                        }
                        if (nbbyteremaining > 0)//nbbyteremaining < buffer_size we should send a buffer with length=nbbyteremaining
                        {
                            // send the end of the data
                            if (!this.datasocket.Connected)
                            {
                                return;
                            }
                            data_send_size   = datasocket.Send(local_buffer, cpt * buffer_size, nbbyteremaining, SocketFlags.None);
                            nbbytesent      += data_send_size;
                            nbbyteremaining -= data_send_size;
                            //event send progress
                            if (this.event_Socket_Data_Send_Progress != null)
                            {
                                this.event_Socket_Data_Send_Progress(this, new EventArgs_Send_Progress_Socket_Data(nbbytesent, nbbyteremaining, bufsize));
                            }
                        }
                        if (b_send_sent_completed)
                        {
                            //event send completed
                            if (this.event_Socket_Data_Send_Completed != null)
                            {
                                this.event_Socket_Data_Send_Completed(this, new EventArgs());
                            }
                        }
                    }
                    b_send_sent_completed = true;
                }
            }
            catch (Exception e)
            {
                // remove all data to be send
                this.evt_unlocked_send_queue.WaitOne();
                this.send_queue.Clear();
                this.evt_unlocked_send_queue.Set();

                // restart thread to send data
                ThreadStart myThreadStart = new ThreadStart(this.my_send);
                this.SendThread = new Thread(myThreadStart);
                this.SendThread.Start();
                if (this.locally_closed)
                {
                    return;
                }
                if (e is SocketException)
                {
                    SocketException se = (SocketException)e;
                    if (se.ErrorCode == 10004) // close methode as been called
                    {
                        return;
                    }

                    this.close();
                    if (se.ErrorCode == 10053) // socket closed by remote side
                    {
                        this.Threaded_event_Socket_Data_Closed_by_Remote_Side();
                        return;
                    }
                }
                this.Threaded_event_Socket_Data_Error(e);
            }
        }
예제 #59
0
 internal ImageComparisonResult(int index, WaitHandle waitHandle)
 {
     _index      = index;
     _waitHandle = waitHandle;
 }
예제 #60
0
        protected int GetResponse(ModbusDataStruct Response)
        {
            int  RecLength   = 0;
            int  Timer       = 0;
            bool RecSomeData = false;
            bool NoMoreData  = false;

            m_Input.Initialize();
            try
            {
                if (IsConnected())
                {
                    //m_Input = m_Client.Receive(ref m_RemoteIpEndPoint); //would block on disconnect!
                    IAsyncResult ar = m_Client.BeginReceive(null, null);
                    System.Threading.WaitHandle wh = ar.AsyncWaitHandle;

                    //because its not possible to set TO, we work async and terminate after some seconds

                    /*while (!ar.IsCompleted)
                     * {
                     *  Thread.Sleep(10);
                     *  Timer += 10;
                     *  if (Timer > RequestTO)
                     *  {
                     *      m_Client.Close();
                     *      throw new TimeoutException();
                     *  }
                     * }*/
                    if (!ar.AsyncWaitHandle.WaitOne(TimeSpan.FromMilliseconds(RequestTO), false))
                    {
                        m_Client.Close();
                        throw new TimeoutException();
                    }
                    m_Input   = m_Client.EndReceive(ar, ref m_RemoteIpEndPoint);
                    RecLength = m_Input.Length;
                    Response.SetAsBytes(m_Input, RecLength);

                    /*while (Timer < RequestTO && !NoMoreData)
                     * {
                     *  System.Threading.Thread.Sleep(10);
                     *  Timer = Timer + (10);
                     *  if (m_Stream.DataAvailable)
                     *  {
                     *      RecLength = RecLength + m_Stream.Read(m_Input, RecLength, m_Input.Length);
                     *      RecSomeData = true;
                     *  }
                     *  else
                     *  {
                     *      NoMoreData = RecSomeData;   //quit Timeout if some Data was received and no more is following
                     *  }
                     * };*/
                }
                ;
            }
            catch (TimeoutException exception)
            {
                OnMBusException(ModBusException.ModBusExceptionCodeEnum.NoNetworkConnection);
            }
            catch (SocketException exception)
            {
                if (exception.ErrorCode == 10061 | exception.ErrorCode == 10060)
                {//10061 "No connection could be made because the target machine actively refused it"
                    OnMBusException(ModBusException.ModBusExceptionCodeEnum.NoNetworkConnection);
                }
                else
                {
                    OnMBusException(ModBusException.ModBusExceptionCodeEnum.NetworkError);
                    Console.WriteLine(exception.ToString() + " " + exception.ErrorCode.ToString()); //??
                }
            }
            finally
            {
                //    wh.Close();
            }

            return(RecLength);
        }