Пример #1
0
		public void Disposed_Set ()
		{
			var ewh = new EventWaitHandle (false, EventResetMode.ManualReset);
			ewh.Dispose();
			try {
				ewh.Set();
				Assert.Fail ();
			} catch (ObjectDisposedException) {
			}
		}
Пример #2
0
        public void CleanUp()
        {
            target?.Dispose();

            waitHandle?.Dispose();

            stateWaitHandle?.Dispose();

            HangUpConnectionById(entryId);
            HangUpConnectionById(invalidEntryId);
        }
Пример #3
0
        private void Dispose(bool disposing)
        {
            if (disposing)
            {
                if (_fDisposed)
                {
                    throw new ObjectDisposedException(null);
                }

                if (WaitingReadCount > 0 || WaitingUpgradeCount > 0 || WaitingWriteCount > 0)
                {
                    throw new SynchronizationLockException(SR.SynchronizationLockException_IncorrectDispose);
                }

                if (IsReadLockHeld || IsUpgradeableReadLockHeld || IsWriteLockHeld)
                {
                    throw new SynchronizationLockException(SR.SynchronizationLockException_IncorrectDispose);
                }

                if (_writeEvent != null)
                {
                    _writeEvent.Dispose();
                    _writeEvent = null;
                }

                if (_readEvent != null)
                {
                    _readEvent.Dispose();
                    _readEvent = null;
                }

                if (_upgradeEvent != null)
                {
                    _upgradeEvent.Dispose();
                    _upgradeEvent = null;
                }

                if (_waitUpgradeEvent != null)
                {
                    _waitUpgradeEvent.Dispose();
                    _waitUpgradeEvent = null;
                }

                _fDisposed = true;
            }
        }
        /// <summary>
        /// Opens the server channel, including aborting any existing channels
        /// and retrying.
        /// </summary>
        internal static bool OpenChannel(int retries, out IChannel channel, out EventWaitHandle notifyEvent)
        {
            // If anyone else is listening, abort them so they close the channel
            using (var evt = GetNotifyEvent()) {
                if (evt != null) {
                    evt.Set();
                }
            }

            channel = null;
            notifyEvent = null;

            while (retries-- > 0) {
                try {
                    // We have to open an IPC channel with a single global name,
                    // since our test adapter has no way to know which VS
                    // instance started it. We will only keep the channel open
                    // for a short period, and close it immediately when we stop
                    // debugging. As long as you don't attempt to debug two unit
                    // tests in two different VS instances at the same time,
                    // nobody should get confused.
                    notifyEvent = CreateNotifyEvent();
                    channel = Internal.VSTestHostPackage.RegisterChannel(DebugConnectionChannelName);
                    return true;
                } catch (RemotingException) {
                    // Someone else is already listening, so we need to abort
                    // them and try again.
                    using (var evt = GetNotifyEvent()) {
                        if (evt != null) {
                            evt.Set();
                        }
                    }
                }
            }

            if (channel != null) {
                ChannelServices.UnregisterChannel(channel);
                channel = null;
            }
            if (notifyEvent != null) {
                notifyEvent.Dispose();
                notifyEvent = null;
            }
            return false;
        }
        private void read_events_thread() {

            string prefix = use_global_ ? "Global\\" : "";
            try {
                memory_file_ = MemoryMappedFile.CreateNew(prefix + "DBWIN_BUFFER", 4096L);

                bool created = false;
                buffer_ready_ = new EventWaitHandle( false, EventResetMode.AutoReset, prefix + "DBWIN_BUFFER_READY", out created);
                if (!created) 
                    errors_.add("Can't create the DBWIN_BUFFER_READY event/" + use_global_);

                if (created) {
                    data_ready_ = new EventWaitHandle(false, EventResetMode.AutoReset, prefix + "DBWIN_DATA_READY", out created);
                    if (!created) 
                        errors_.add("Can't create the DBWIN_DATA_READY event/" + use_global_);
                }

                if (created) {
                    buffer_ready_.Set();
                    while (!disposed_) {
                        if (!data_ready_.WaitOne(1000))
                            continue;

                        using (var stream = memory_file_.CreateViewStream()) {
                            using (var reader = new BinaryReader(stream, Encoding.Default)) {
                                var process_id = (int)reader.ReadUInt32();
                                var raw = reader.ReadChars(4092);
                                var idx = Array.IndexOf(raw, '\0');
                                var msg = new string(raw, 0, idx);
                                find_process_id(process_id);
                                string process_name = pid_to_name_.ContainsKey(process_id) ? pid_to_name_[process_id] : "";
                                lock (this)
                                    events_.Add(new debug_event {
                                        unique_id = next_unique_id++, process_id = process_id, msg = msg, lo_process_name = process_name
                                    });
                            }
                        }
                
                        buffer_ready_.Set();
                    }
                }
            } catch (Exception e) {
                logger.Fatal("Can't read debug events " + e.Message);
                errors_.add("Error reading debug events " + e.Message);
            }

            if ( memory_file_ != null)
                memory_file_.Dispose();
            if ( data_ready_ != null)
                data_ready_.Dispose();
            if ( buffer_ready_ != null)
                buffer_ready_.Dispose();

        }
Пример #6
0
		public DoubleLaunchLocker(string signalId, string waitId, bool force = false, Action shuttingDown = null)
		{
			SignalId = signalId;
			WaitId = waitId;
			_force = force;
			ShuttingDown = shuttingDown;

			bool isNew;
			_signalHandler = new EventWaitHandle(false, EventResetMode.AutoReset, signalId, out isNew);
			if (!isNew)
			{
				Application.Current.ShutdownMode = ShutdownMode.OnExplicitShutdown;
				bool terminate = false;
				if (!force && !RequestConfirmation())
					terminate = true;
				if (!terminate)
				{
					_waitHandler = new EventWaitHandle(false, EventResetMode.AutoReset, waitId);
					_signalHandler.Dispose();
					_signalHandler = new EventWaitHandle(false, EventResetMode.ManualReset, signalId, out isNew);
					if (!isNew)
					{
						_signalHandler.Set();
						terminate = !_waitHandler.WaitOne(TIMEOUT);
					}
				}
				if (terminate)
				{
					TryShutdown();
					ForceShutdown();
				}
				else
					Application.Current.ShutdownMode = ShutdownMode.OnLastWindowClose;
			}
			ThreadPool.QueueUserWorkItem(WaitingHandler, waitId);
		}
Пример #7
0
        public static void Start() {
            if (_listenTask == null) {
                lock (typeof (Monitor)) {
                    _cancellationTokenSource = new CancellationTokenSource();

                    bool wasCreated;
                    var ewhSec = new EventWaitHandleSecurity();
                    ewhSec.AddAccessRule(
                        new EventWaitHandleAccessRule(
                            new SecurityIdentifier(WellKnownSidType.WorldSid, null), EventWaitHandleRights.FullControl, AccessControlType.Allow));

                    var sessionAckEvent = new EventWaitHandle(false, EventResetMode.AutoReset, "DBWIN_BUFFER_READY", out wasCreated, ewhSec);
                    var sessionReadyEvent = new EventWaitHandle(false, EventResetMode.AutoReset, "DBWIN_DATA_READY", out wasCreated, ewhSec);
                    var globalAckEvent = new EventWaitHandle(false, EventResetMode.AutoReset, "Global\\DBWIN_BUFFER_READY", out wasCreated, ewhSec);
                    var globalReadyEvent = new EventWaitHandle(false, EventResetMode.AutoReset, "Global\\DBWIN_DATA_READY", out wasCreated, ewhSec);

                    var sd = new SECURITY_DESCRIPTOR();
                    var sa = new SECURITY_ATTRIBUTES();

                    // Initialize the security descriptor.
                    if (!Advapi32.InitializeSecurityDescriptor(ref sd, 1)) {
                        throw new ApplicationException(
                            string.Format("{0}. Last Win32 Error was {1}", "Failed to initializes the security descriptor.", Marshal.GetLastWin32Error()));
                    }

                    // Set information in a discretionary access control list
                    if (!Advapi32.SetSecurityDescriptorDacl(ref sd, true, IntPtr.Zero, false)) {
                        throw new ApplicationException(
                            string.Format("{0}. Last Win32 Error was {1}", "Failed to initializes the security descriptor", Marshal.GetLastWin32Error()));
                    }

                    // Create the event for slot 'DBWIN_BUFFER_READY'
                    sa.nLength = Marshal.SizeOf(sa);
                    sa.lpSecurityDescriptor = Marshal.AllocHGlobal(Marshal.SizeOf(sd));
                    Marshal.StructureToPtr(sd, sa.lpSecurityDescriptor, false);

                    // Get a handle to the readable shared memory at slot 'DBWIN_BUFFER'.
                    var sessionSharedFileHandle = Kernel32.CreateFileMapping(new IntPtr(-1), ref sa, PageProtection.ReadWrite, 0, 4096, "DBWIN_BUFFER");
                    if (sessionSharedFileHandle == IntPtr.Zero) {
                        throw new ApplicationException(
                            string.Format(
                                "{0}. Last Win32 Error was {1}", "Failed to create a file mapping to slot 'DBWIN_BUFFER'", Marshal.GetLastWin32Error()));
                    }

                    // Create a view for this file mapping so we can access it
                    var sessionSharedMemoryHandle = Kernel32.MapViewOfFile(sessionSharedFileHandle, /*SECTION_MAP_READ*/ 0x0004, 0, 0, 4096);
                    if (sessionSharedMemoryHandle == IntPtr.Zero) {
                        throw new ApplicationException(
                            string.Format(
                                "{0}. Last Win32 Error was {1}", "Failed to create a mapping view for slot 'DBWIN_BUFFER'", Marshal.GetLastWin32Error()));
                    }

                    // Get a handle to the readable shared memory at slot 'DBWIN_BUFFER'.
                    var globalSharedFileHandle = Kernel32.CreateFileMapping(new IntPtr(-1), ref sa, PageProtection.ReadWrite, 0, 4096, "Global\\DBWIN_BUFFER");
                    if (globalSharedFileHandle == IntPtr.Zero) {
                        throw new ApplicationException(
                            string.Format(
                                "{0}. Last Win32 Error was {1}", "Failed to create a file mapping to slot 'Global\\DBWIN_BUFFER'", Marshal.GetLastWin32Error()));
                    }

                    // Create a view for this file mapping so we can access it
                    var globalSharedMemoryHandle = Kernel32.MapViewOfFile(globalSharedFileHandle, /*SECTION_MAP_READ*/ 0x0004, 0, 0, 4096);
                    if (globalSharedMemoryHandle == IntPtr.Zero) {
                        throw new ApplicationException(
                            string.Format(
                                "{0}. Last Win32 Error was {1}", "Failed to create a mapping view for slot 'Global\\DBWIN_BUFFER'", Marshal.GetLastWin32Error()));
                    }

                    var queue = new Queue<Tuple<int, DateTime, string>>();
                    var dataAvailable = new ManualResetEvent(true);

                    _listenTask = Task.Factory.StartNew(
                        () => {
                            // Everything after the first DWORD is our debugging text
                            IntPtr sessionStringPointer;
                            IntPtr globalStringPointer;

                            if (Environment.Is64BitProcess) {
                                sessionStringPointer = new IntPtr(sessionSharedMemoryHandle.ToInt64() + Marshal.SizeOf(typeof (int)));
                                globalStringPointer = new IntPtr(globalSharedMemoryHandle.ToInt64() + Marshal.SizeOf(typeof (int)));
                            } else {
                                sessionStringPointer = new IntPtr(sessionSharedMemoryHandle.ToInt32() + Marshal.SizeOf(typeof (int)));
                                globalStringPointer = new IntPtr(globalSharedMemoryHandle.ToInt32() + Marshal.SizeOf(typeof (int)));
                            }

                            while (!_cancellationTokenSource.IsCancellationRequested) {
                                sessionAckEvent.Set();
                                globalAckEvent.Set();

                                try {
                                    var i = WaitHandle.WaitAny(new[] {
                                        sessionReadyEvent, globalReadyEvent, _cancellationTokenSource.Token.WaitHandle
                                    });
                                    var now = DateTime.Now;
                                    if (i == 0) {
                                        lock (queue) {
                                            queue.Enqueue(new Tuple<int, DateTime, string>(Marshal.ReadInt32(sessionSharedMemoryHandle), now, Marshal.PtrToStringAnsi(sessionStringPointer)));
                                            dataAvailable.Set();
                                        }
                                    }

                                    if (i == 1) {
                                        lock (queue) {
                                            queue.Enqueue(new Tuple<int, DateTime, string>(Marshal.ReadInt32(globalSharedMemoryHandle), now, Marshal.PtrToStringAnsi(globalStringPointer)));
                                            dataAvailable.Set();
                                        }
                                    }
                                } catch {
                                    // it's over. 
                                    _cancellationTokenSource.Cancel();
                                }
                            }
                            _listenTask = null;

                            // cleanup after stopping.
                            globalAckEvent.Reset();
                            globalAckEvent.Dispose();
                            globalAckEvent = null;

                            sessionAckEvent.Reset();
                            sessionAckEvent.Dispose();
                            sessionAckEvent = null;

                            globalReadyEvent.Reset();
                            globalReadyEvent.Dispose();
                            globalReadyEvent = null;

                            sessionReadyEvent.Reset();
                            sessionReadyEvent.Dispose();
                            sessionReadyEvent = null;

                            // Close SharedFile
                            if (sessionSharedFileHandle != IntPtr.Zero) {
                                if (!Kernel32.CloseHandle(sessionSharedFileHandle)) {
                                    throw new ApplicationException(
                                        string.Format("{0}. Last Win32 Error was {1}", "Failed to close handle for 'SharedFile'", Marshal.GetLastWin32Error()));
                                }
                                sessionSharedFileHandle = IntPtr.Zero;
                            }

                            // Unmap SharedMem
                            if (sessionSharedMemoryHandle != IntPtr.Zero) {
                                if (!Kernel32.UnmapViewOfFile(sessionSharedMemoryHandle)) {
                                    throw new ApplicationException(
                                        string.Format(
                                            "{0}. Last Win32 Error was {1}", "Failed to unmap view for slot 'DBWIN_BUFFER'", Marshal.GetLastWin32Error()));
                                }
                                sessionSharedMemoryHandle = IntPtr.Zero;
                            }

                            // Close SharedFile
                            if (globalSharedFileHandle != IntPtr.Zero) {
                                if (!Kernel32.CloseHandle(globalSharedFileHandle)) {
                                    throw new ApplicationException(
                                        string.Format("{0}. Last Win32 Error was {1}", "Failed to close handle for 'SharedFile'", Marshal.GetLastWin32Error()));
                                }
                                globalSharedFileHandle = IntPtr.Zero;
                            }

                            // Unmap SharedMem
                            if (globalSharedMemoryHandle != IntPtr.Zero) {
                                if (!Kernel32.UnmapViewOfFile(globalSharedMemoryHandle)) {
                                    throw new ApplicationException(
                                        string.Format(
                                            "{0}. Last Win32 Error was {1}", "Failed to unmap view for slot 'Global\\DBWIN_BUFFER'", Marshal.GetLastWin32Error()));
                                }
                                globalSharedMemoryHandle = IntPtr.Zero;
                            }
                        }, _cancellationTokenSource.Token);

                    Task.Factory.StartNew(() => {
                        // handle events on seperate task to minimize the work that is done blocking the handles
                        Tuple<int, DateTime, string> item = null;

                        while (WaitHandle.WaitAny(new[] {
                            dataAvailable, _cancellationTokenSource.Token.WaitHandle
                        }) == 0) {
                            lock (queue) {
                                if (queue.Count > 0) {
                                    item = queue.Dequeue();
                                }
                                if (queue.Count == 0) {
                                    dataAvailable.Reset();
                                }
                            }

                            if (item == null || OnOutputDebugString == null) {
                                continue;
                            }

                            try {
                                OnOutputDebugString(new OutputDebugStringEventArgs(item.Item1, item.Item2, item.Item3));
                            } catch {
                                // if it's taken, good, if not--well too bad!
                            }
                        }
                    }, _cancellationTokenSource.Token);
                }
            }
        }
        public override string ResolveToString()
        {
            if (!Parameters.Contains("url") || string.IsNullOrEmpty(Parameters["url"].ToString()))
                throw new InvalidOperationException();

            string url = Parameters["url"].ToString();

            string resultString = null;

            using (var wc = new WebClient())
            {
                var tlock = new EventWaitHandle(false, EventResetMode.ManualReset);
                wc.DownloadProgressChanged += new DownloadProgressChangedEventHandler((sender, e) =>
                {
                    // TODO: Add progress monitoring
                });
                wc.DownloadStringCompleted += new DownloadStringCompletedEventHandler((sender, e) =>
                {
                    resultString = e.Result;
                    tlock.Set();
                });
                wc.DownloadStringAsync(new Uri(url));
                tlock.WaitOne();
                tlock.Dispose();
            }

            return resultString;
        }
Пример #9
0
 public void Dispose()
 {
     eventWaitHandle.Dispose();
 }
Пример #10
0
        private void RunTest()
        {
            Logger logger = eventLogControl.Logger;
            MetaDictionary globals = new MetaDictionary();
            EventWaitHandle endEvent = new EventWaitHandle(false, EventResetMode.ManualReset);

            try
            {
                CancellationTokenSource tokenSource = new CancellationTokenSource();
                using (TestDocument.TestGraphContainer testGraph = Document.CreateTestGraph(logger, globals))
                {
                    testGraph.Graph.LogPacketEvent += new EventHandler<LogPacketEventArgs>(log_AddLogPacket);
                    testGraph.Graph.EditPacketEvent += new EventHandler<EditPacketEventArgs>(Graph_EditPacketEvent);

                    LogPacket[] packets = Document.GetInputPackets();

                    using (QueuedDataAdapter inputAdapter = new QueuedDataAdapter(tokenSource.Token))
                    {
                        foreach (LogPacket p in packets)
                        {
                            inputAdapter.Enqueue(p.Frame.CloneFrame());
                        }

                        inputAdapter.StopEnqueue();

                        testGraph.Graph.BindEndpoint(testGraph.Output.Uuid, new EventDataAdapter(endEvent));
                        testGraph.Graph.BindEndpoint(testGraph.Input.Uuid, inputAdapter);

                        IPipelineEndpoint inputEndpoint = testGraph.Input as IPipelineEndpoint;
                        inputEndpoint.Start();

                        // Sleep up to 100 seconds
                        if (!endEvent.WaitOne(100000))
                        {
                            logger.LogError("Test did not finish after 100 seconds");
                            tokenSource.Cancel();
                        }
                    }
                }
            }
            catch (EndOfStreamException)
            {
                // End of stream
            }
            catch (ThreadAbortException)
            {
            }
            catch (ObjectDisposedException)
            {
            }
            finally
            {
                if(endEvent != null)
                {
                    endEvent.Dispose();
                }
            }
        }