示例#1
0
文件: test.cs 项目: mono/gert
	static IAsyncResult BeginGetRequestStreamWithTimeout (HttpWebRequest request, AsyncCallback callback, object state, out RegisteredWaitHandle handle)
	{
		IAsyncResult asyncResult = request.BeginGetRequestStream (callback, state);

		handle = ThreadPool.RegisterWaitForSingleObject (
			asyncResult.AsyncWaitHandle,
			CancelRequest,
			request,
			1000,
			true);

		return asyncResult;
	}
示例#2
0
 public BlockChecker()
 {
     this.InitializeFinish += this.BlockChecker_InitializeFinish;
     this._registration     = this.RegisterSendTimeout();
 }
示例#3
0
        public static void QueueRegisterPositiveAndFlowTest()
        {
            var asyncLocal = new AsyncLocal <int>();

            asyncLocal.Value = 1;

            var obj = new object();
            var registerWaitEvent = new AutoResetEvent(false);
            var threadDone        = new AutoResetEvent(false);
            RegisteredWaitHandle registeredWaitHandle = null;
            Exception            backgroundEx         = null;
            int backgroundAsyncLocalValue             = 0;

            Action <bool, Action> commonBackgroundTest =
                (isRegisteredWaitCallback, test) =>
            {
                try
                {
                    if (isRegisteredWaitCallback)
                    {
                        RegisteredWaitHandle toUnregister = registeredWaitHandle;
                        registeredWaitHandle = null;
                        Assert.True(toUnregister.Unregister(threadDone));
                    }
                    test();
                    backgroundAsyncLocalValue = asyncLocal.Value;
                }
                catch (Exception ex)
                {
                    backgroundEx = ex;
                }
                finally
                {
                    if (!isRegisteredWaitCallback)
                    {
                        threadDone.Set();
                    }
                }
            };
            Action <bool> waitForBackgroundWork =
                isWaitForRegisteredWaitCallback =>
            {
                if (isWaitForRegisteredWaitCallback)
                {
                    registerWaitEvent.Set();
                }
                threadDone.CheckedWait();
                if (backgroundEx != null)
                {
                    throw new AggregateException(backgroundEx);
                }
            };

            ThreadPool.QueueUserWorkItem(
                state =>
            {
                commonBackgroundTest(false, () =>
                {
                    Assert.Same(obj, state);
                });
            },
                obj);
            waitForBackgroundWork(false);
            Assert.Equal(1, backgroundAsyncLocalValue);

            ThreadPool.UnsafeQueueUserWorkItem(
                state =>
            {
                commonBackgroundTest(false, () =>
                {
                    Assert.Same(obj, state);
                });
            },
                obj);
            waitForBackgroundWork(false);
            Assert.Equal(0, backgroundAsyncLocalValue);

            registeredWaitHandle =
                ThreadPool.RegisterWaitForSingleObject(
                    registerWaitEvent,
                    (state, timedOut) =>
            {
                commonBackgroundTest(true, () =>
                {
                    Assert.Same(obj, state);
                    Assert.False(timedOut);
                });
            },
                    obj,
                    UnexpectedTimeoutMilliseconds,
                    false);
            waitForBackgroundWork(true);
            Assert.Equal(1, backgroundAsyncLocalValue);

            registeredWaitHandle =
                ThreadPool.UnsafeRegisterWaitForSingleObject(
                    registerWaitEvent,
                    (state, timedOut) =>
            {
                commonBackgroundTest(true, () =>
                {
                    Assert.Same(obj, state);
                    Assert.False(timedOut);
                });
            },
                    obj,
                    UnexpectedTimeoutMilliseconds,
                    false);
            waitForBackgroundWork(true);
            Assert.Equal(0, backgroundAsyncLocalValue);
        }
        internal static void WriteToSync <T>(this Stream stream, Stream toStream, long?copyLength, long?maxLength, bool calculateMd5, bool syncRead, ExecutionState <T> executionState, StreamDescriptor streamCopyState)
        {
            if (copyLength.HasValue && maxLength.HasValue)
            {
                throw new ArgumentException(SR.StreamLengthMismatch);
            }

            if (stream.CanSeek && maxLength.HasValue && stream.Length - stream.Position > maxLength)
            {
                throw new InvalidOperationException(SR.StreamLengthError);
            }

            if (stream.CanSeek && copyLength.HasValue && stream.Length - stream.Position < copyLength)
            {
                throw new ArgumentOutOfRangeException("copyLength", SR.StreamLengthShortError);
            }

            byte[] buffer = new byte[GetBufferSize(stream)];

            if (streamCopyState != null && calculateMd5 && streamCopyState.Md5HashRef == null)
            {
                streamCopyState.Md5HashRef = new MD5Wrapper();
            }

            RegisteredWaitHandle waitHandle     = null;
            ManualResetEvent     completedEvent = null;

            if (!syncRead && executionState.OperationExpiryTime.HasValue)
            {
                completedEvent = new ManualResetEvent(false);
                waitHandle     = ThreadPool.RegisterWaitForSingleObject(
                    completedEvent,
                    StreamExtensions.MaximumCopyTimeCallback <T>,
                    executionState,
                    executionState.RemainingTimeout,
                    true);
            }

            try
            {
                long?bytesRemaining = copyLength;
                int  readCount;
                do
                {
                    if (executionState.OperationExpiryTime.HasValue && DateTime.Now.CompareTo(executionState.OperationExpiryTime.Value) > 0)
                    {
                        throw Exceptions.GenerateTimeoutException(executionState.Cmd != null ? executionState.Cmd.CurrentResult : null, null);
                    }

                    // Determine how many bytes to read this time so that no more than copyLength bytes are read
                    int bytesToRead = MinBytesToRead(bytesRemaining, buffer.Length);

                    if (bytesToRead == 0)
                    {
                        break;
                    }

                    // Read synchronously or asynchronously
                    readCount = syncRead
                                    ? stream.Read(buffer, 0, bytesToRead)
                                    : stream.EndRead(stream.BeginRead(buffer, 0, bytesToRead, null /* Callback */, null /* State */));

                    // Decrement bytes to write from bytes read
                    if (bytesRemaining.HasValue)
                    {
                        bytesRemaining -= readCount;
                    }

                    // Write
                    if (readCount > 0)
                    {
                        toStream.Write(buffer, 0, readCount);

                        // Update the StreamDescriptor after the bytes are successfully committed to the output stream
                        if (streamCopyState != null)
                        {
                            streamCopyState.Length += readCount;

                            if (maxLength.HasValue && streamCopyState.Length > maxLength.Value)
                            {
                                throw new InvalidOperationException(SR.StreamLengthError);
                            }

                            if (streamCopyState.Md5HashRef != null)
                            {
                                streamCopyState.Md5HashRef.UpdateHash(buffer, 0, readCount);
                            }
                        }
                    }
                }while (readCount != 0);

                if (bytesRemaining.HasValue && bytesRemaining != 0)
                {
                    throw new ArgumentOutOfRangeException("copyLength", SR.StreamLengthShortError);
                }
            }
            catch (Exception)
            {
                if (executionState.OperationExpiryTime.HasValue && DateTime.Now.CompareTo(executionState.OperationExpiryTime.Value) > 0)
                {
                    throw Exceptions.GenerateTimeoutException(executionState.Cmd != null ? executionState.Cmd.CurrentResult : null, null);
                }
                else
                {
                    throw;
                }
            }
            finally
            {
                if (waitHandle != null)
                {
                    waitHandle.Unregister(null);
                }

                if (completedEvent != null)
                {
                    completedEvent.Close();
                }
            }

            if (streamCopyState != null && streamCopyState.Md5HashRef != null)
            {
                streamCopyState.Md5        = streamCopyState.Md5HashRef.ComputeHash();
                streamCopyState.Md5HashRef = null;
            }
        }
示例#5
0
        public void Start(
            Guid payloadGuid,
            ArraySegment <byte> payloadData,
            SafeFileHandle inheritableReportHandle,
            string dllNameX64,
            string dllNameX86)
        {
            using (m_syncSemaphore.AcquireSemaphore())
            {
                if (m_starting || m_disposed)
                {
                    throw new InvalidOperationException("Cannot invoke start process more than once or after this instance has been Disposed.");
                }

                m_starting = true;

                bool redirectStreams = m_errorDataReceived != null || m_outputDataReceived != null;

                // The process creation flags:
                // - We use CREATE_DEFAULT_ERROR_MODE to ensure that the hard error mode of the child process (i.e., GetErrorMode)
                //   is deterministic. Inheriting error mode is the default, but there may be some concurrent operation that temporarily
                //   changes it (process global). The CLR has been observed to do so.
                // - We use CREATE_NO_WINDOW when redirecting stdout/err/in and there is a parent console (to prevent creating extra conhost.exe
                //   processes on Windows when running headless) or when console sharing is disabled (typical for BuildXL which takes over
                //   management of the console). Otherwise we use the parent console for output.
                int creationFlags = Native.Processes.ProcessUtilities.CREATE_DEFAULT_ERROR_MODE;
                if (redirectStreams && (s_consoleWindow != IntPtr.Zero || m_disableConHostSharing))
                {
                    creationFlags |= Native.Processes.ProcessUtilities.CREATE_NO_WINDOW;
                }

                SafeFileHandle standardInputWritePipeHandle = null;
                SafeFileHandle standardOutputReadPipeHandle = null;
                SafeFileHandle standardErrorReadPipeHandle  = null;

                try
                {
                    // set up the environment block parameter
                    var environmentHandle = default(GCHandle);
                    var payloadHandle     = default(GCHandle);

                    SafeFileHandle   hStdInput    = null;
                    SafeFileHandle   hStdOutput   = null;
                    SafeFileHandle   hStdError    = null;
                    SafeThreadHandle threadHandle = null;
                    try
                    {
                        IntPtr environmentPtr = IntPtr.Zero;
                        if (m_unicodeEnvironmentBlock != null)
                        {
                            creationFlags    |= Native.Processes.ProcessUtilities.CREATE_UNICODE_ENVIRONMENT;
                            environmentHandle = GCHandle.Alloc(m_unicodeEnvironmentBlock, GCHandleType.Pinned);
                            environmentPtr    = environmentHandle.AddrOfPinnedObject();
                        }

                        if (redirectStreams)
                        {
                            Pipes.CreateInheritablePipe(
                                Pipes.PipeInheritance.InheritRead,
                                Pipes.PipeFlags.WriteSideAsync,
                                readHandle: out hStdInput,
                                writeHandle: out standardInputWritePipeHandle);
                        }
                        else
                        {
                            // Avoid stdin hooking when not needed.
                            hStdInput = new SafeFileHandle(new IntPtr(-1), true);
                        }

                        if (m_outputDataReceived != null)
                        {
                            Pipes.CreateInheritablePipe(
                                Pipes.PipeInheritance.InheritWrite,
                                Pipes.PipeFlags.ReadSideAsync,
                                readHandle: out standardOutputReadPipeHandle,
                                writeHandle: out hStdOutput);
                        }
                        else
                        {
                            // Pass through to the parent console.
                            hStdOutput = new SafeFileHandle(new IntPtr(-1), true);
                        }

                        if (m_errorDataReceived != null)
                        {
                            Pipes.CreateInheritablePipe(
                                Pipes.PipeInheritance.InheritWrite,
                                Pipes.PipeFlags.ReadSideAsync,
                                readHandle: out standardErrorReadPipeHandle,
                                writeHandle: out hStdError);
                        }
                        else
                        {
                            // Pass through to the parent console.
                            hStdError = new SafeFileHandle(new IntPtr(-1), true);
                        }

                        // We want a per-process job primarily. If nested job support is not available, then we make sure to not have a BuildXL-level job.
                        if (JobObject.OSSupportsNestedJobs && m_createJobObjectForCurrentProcess)
                        {
                            JobObject.SetTerminateOnCloseOnCurrentProcessJob();
                        }

                        // Initialize the injector
                        m_processInjector = new ProcessTreeContext(
                            payloadGuid,
                            inheritableReportHandle,
                            payloadData,
                            dllNameX64,
                            dllNameX86,
                            m_numRetriesPipeReadOnCancel,
                            m_debugPipeReporter,
                            m_loggingContext);

                        // If path remapping is enabled then we wrap the job object in a container, so the filter drivers get
                        // configured (and they get cleaned up when the container is disposed)
                        if (m_containerConfiguration.IsIsolationEnabled)
                        {
                            m_job = new Container(
                                name: null,
                                containerConfiguration: m_containerConfiguration,
                                loggingContext: m_loggingContext);
                        }
                        else
                        {
                            m_job = new JobObject(null);
                        }

                        // We want the effects of SEM_NOGPFAULTERRORBOX on all children (but can't set that with CreateProcess).
                        // That's not set otherwise (even if set in this process) due to CREATE_DEFAULT_ERROR_MODE above.
                        m_job.SetLimitInformation(terminateOnClose: true, failCriticalErrors: false, allowProcessesToBreakAway: m_setJobBreakawayOk);

                        m_processInjector.Listen();

                        if (m_containerConfiguration.IsIsolationEnabled)
                        {
                            // After calling SetLimitInformation, start up the container if present
                            // This will throw if the container is not set up properly
                            m_job.StartContainerIfPresent();
                        }

                        // The call to the CreateDetouredProcess below will add a newly created process to the job.
                        System.Diagnostics.Stopwatch m_startUpTimeWatch = System.Diagnostics.Stopwatch.StartNew();
                        var detouredProcessCreationStatus =
                            Native.Processes.ProcessUtilities.CreateDetouredProcess(
                                m_commandLine,
                                creationFlags,
                                environmentPtr,
                                m_workingDirectory,
                                hStdInput,
                                hStdOutput,
                                hStdError,
                                m_job,
                                m_processInjector.Injector,
                                m_containerConfiguration.IsIsolationEnabled,
                                out m_processHandle,
                                out threadHandle,
                                out m_processId,
                                out int errorCode);
                        m_startUpTimeWatch.Stop();
                        m_startUpTime = m_startUpTimeWatch.ElapsedMilliseconds;

                        if (detouredProcessCreationStatus != CreateDetouredProcessStatus.Succeeded)
                        {
                            // TODO: Indicating user vs. internal errors (and particular phase failures e.g. adding to job object or injecting detours)
                            //       is good progress on the transparency into these failures. But consider making this indication visible beyond this
                            //       function without throwing exceptions; consider returning a structured value or logging events.
                            string message;
                            if (detouredProcessCreationStatus.IsDetoursSpecific())
                            {
                                message = string.Format(
                                    CultureInfo.InvariantCulture,
                                    "Internal error during process creation: {0:G}",
                                    detouredProcessCreationStatus);
                            }
                            else if (detouredProcessCreationStatus == CreateDetouredProcessStatus.ProcessCreationFailed)
                            {
                                message = "Process creation failed";
                            }
                            else
                            {
                                message = string.Format(
                                    CultureInfo.InvariantCulture,
                                    "Process creation failed: {0:G}",
                                    detouredProcessCreationStatus);
                            }

                            throw new BuildXLException(
                                      message,
                                      new NativeWin32Exception(errorCode));
                        }

                        // TODO: We should establish good post-conditions for CreateDetouredProcess. As a temporary measure, it would be nice
                        //       to determine if we are sometimes getting invalid process handles with retVal == true. So for now we differentiate
                        //       that possible case with a unique error string.
                        if (m_processHandle.IsInvalid)
                        {
                            throw new BuildXLException("Unable to start or detour a process (process handle invalid)", new NativeWin32Exception(errorCode));
                        }
                    }
                    finally
                    {
                        if (environmentHandle.IsAllocated)
                        {
                            environmentHandle.Free();
                        }

                        if (payloadHandle.IsAllocated)
                        {
                            payloadHandle.Free();
                        }

                        if (hStdInput != null && !hStdInput.IsInvalid)
                        {
                            hStdInput.Dispose();
                        }

                        if (hStdOutput != null && !hStdOutput.IsInvalid)
                        {
                            hStdOutput.Dispose();
                        }

                        if (hStdError != null && !hStdError.IsInvalid)
                        {
                            hStdError.Dispose();
                        }

                        if (inheritableReportHandle != null && !inheritableReportHandle.IsInvalid)
                        {
                            inheritableReportHandle.Dispose();
                        }

                        if (threadHandle != null && !threadHandle.IsInvalid)
                        {
                            threadHandle.Dispose();
                        }
                    }

                    if (standardInputWritePipeHandle != null)
                    {
                        var standardInputStream = new FileStream(standardInputWritePipeHandle, FileAccess.Write, m_bufferSize, isAsync: true);
                        m_standardInputWriter = new StreamWriter(standardInputStream, m_standardInputEncoding, m_bufferSize)
                        {
                            AutoFlush = true
                        };
                    }

                    if (standardOutputReadPipeHandle != null)
                    {
                        var standardOutputFile = AsyncFileFactory.CreateAsyncFile(
                            standardOutputReadPipeHandle,
                            FileDesiredAccess.GenericRead,
                            ownsHandle: true,
                            kind: FileKind.Pipe);
                        m_outputReader = new AsyncPipeReader(standardOutputFile, m_outputDataReceived, m_standardOutputEncoding, m_bufferSize);
                        m_outputReader.BeginReadLine();
                    }

                    if (standardErrorReadPipeHandle != null)
                    {
                        var standardErrorFile = AsyncFileFactory.CreateAsyncFile(
                            standardErrorReadPipeHandle,
                            FileDesiredAccess.GenericRead,
                            ownsHandle: true,
                            kind: FileKind.Pipe);
                        m_errorReader = new AsyncPipeReader(standardErrorFile, m_errorDataReceived, m_standardErrorEncoding, m_bufferSize);
                        m_errorReader.BeginReadLine();
                    }

                    Contract.Assert(!m_processHandle.IsInvalid);
                    m_processWaitHandle = new SafeWaitHandleFromSafeHandle(m_processHandle);

                    m_waiting = true;

                    TimeSpan timeout = m_timeout ?? Timeout.InfiniteTimeSpan;
                    m_registeredWaitHandle = ThreadPool.RegisterWaitForSingleObject(
                        m_processWaitHandle,
                        CompletionCallbackAsync,
                        null,
                        timeout,
                        true);

                    m_started = true;
                }
                catch (Exception e)
                {
                    if (e is AccessViolationException)
                    {
                        Logger.Log.DetouredProcessAccessViolationException(m_loggingContext, creationFlags + " - " + m_commandLine);
                    }

                    // Dispose pipe handles in case they are not assigned to streams.
                    if (m_standardInputWriter == null)
                    {
                        standardInputWritePipeHandle?.Dispose();
                    }

                    if (m_outputReader == null)
                    {
                        standardOutputReadPipeHandle?.Dispose();
                    }

                    if (m_errorReader == null)
                    {
                        standardErrorReadPipeHandle?.Dispose();
                    }

                    throw;
                }
            }
        }
            private static void StartHelper(NetworkAddressChangedEventHandler caller, bool captureContext, StartIPOptions startIPOptions)
            {
                lock (s_globalLock)
                {
                    // Setup changedEvent and native overlapped struct.
                    if (s_ipv4Socket == null)
                    {
                        int blocking;

                        // Sockets will be initialized by the call to OSSupportsIP*.
                        if (Socket.OSSupportsIPv4)
                        {
                            blocking     = -1;
                            s_ipv4Socket = SafeCloseSocketAndEvent.CreateWSASocketWithEvent(AddressFamily.InterNetwork, SocketType.Dgram, (ProtocolType)0, true, false);
                            Interop.Winsock.ioctlsocket(s_ipv4Socket, Interop.Winsock.IoctlSocketConstants.FIONBIO, ref blocking);
                            s_ipv4WaitHandle = s_ipv4Socket.GetEventHandle();
                        }

                        if (Socket.OSSupportsIPv6)
                        {
                            blocking     = -1;
                            s_ipv6Socket = SafeCloseSocketAndEvent.CreateWSASocketWithEvent(AddressFamily.InterNetworkV6, SocketType.Dgram, (ProtocolType)0, true, false);
                            Interop.Winsock.ioctlsocket(s_ipv6Socket, Interop.Winsock.IoctlSocketConstants.FIONBIO, ref blocking);
                            s_ipv6WaitHandle = s_ipv6Socket.GetEventHandle();
                        }
                    }

                    if ((caller != null) && (!s_callerArray.ContainsKey(caller)))
                    {
                        s_callerArray.Add(caller, captureContext ? ExecutionContext.Capture() : null);
                    }

                    if (s_isListening || s_callerArray.Count == 0)
                    {
                        return;
                    }

                    if (!s_isPending)
                    {
                        int         length;
                        SocketError errorCode;

                        if (Socket.OSSupportsIPv4 && (startIPOptions & StartIPOptions.StartIPv4) != 0)
                        {
                            s_registeredWait = ThreadPool.RegisterWaitForSingleObject(
                                s_ipv4WaitHandle,
                                new WaitOrTimerCallback(AddressChangedCallback),
                                StartIPOptions.StartIPv4,
                                -1,
                                true);

                            errorCode = Interop.Winsock.WSAIoctl_Blocking(
                                s_ipv4Socket.DangerousGetHandle(),
                                (int)IOControlCode.AddressListChange,
                                null, 0, null, 0,
                                out length,
                                IntPtr.Zero, IntPtr.Zero);

                            if (errorCode != SocketError.Success)
                            {
                                NetworkInformationException exception = new NetworkInformationException();
                                if (exception.ErrorCode != (uint)SocketError.WouldBlock)
                                {
                                    throw exception;
                                }
                            }

                            SafeWaitHandle s_ipv4SocketGetEventHandleSafeWaitHandle =
                                s_ipv4Socket.GetEventHandle().GetSafeWaitHandle();

                            errorCode = Interop.Winsock.WSAEventSelect(
                                s_ipv4Socket,
                                s_ipv4SocketGetEventHandleSafeWaitHandle,
                                Interop.Winsock.AsyncEventBits.FdAddressListChange);

                            if (errorCode != SocketError.Success)
                            {
                                throw new NetworkInformationException();
                            }
                        }

                        if (Socket.OSSupportsIPv6 && (startIPOptions & StartIPOptions.StartIPv6) != 0)
                        {
                            s_registeredWait = ThreadPool.RegisterWaitForSingleObject(
                                s_ipv6WaitHandle,
                                new WaitOrTimerCallback(AddressChangedCallback),
                                StartIPOptions.StartIPv6,
                                -1,
                                true);

                            errorCode = Interop.Winsock.WSAIoctl_Blocking(
                                s_ipv6Socket.DangerousGetHandle(),
                                (int)IOControlCode.AddressListChange,
                                null, 0, null, 0,
                                out length,
                                IntPtr.Zero, IntPtr.Zero);

                            if (errorCode != SocketError.Success)
                            {
                                NetworkInformationException exception = new NetworkInformationException();
                                if (exception.ErrorCode != (uint)SocketError.WouldBlock)
                                {
                                    throw exception;
                                }
                            }

                            SafeWaitHandle s_ipv6SocketGetEventHandleSafeWaitHandle =
                                s_ipv6Socket.GetEventHandle().GetSafeWaitHandle();

                            errorCode = Interop.Winsock.WSAEventSelect(
                                s_ipv6Socket,
                                s_ipv6SocketGetEventHandleSafeWaitHandle,
                                Interop.Winsock.AsyncEventBits.FdAddressListChange);

                            if (errorCode != SocketError.Success)
                            {
                                throw new NetworkInformationException();
                            }
                        }
                    }

                    s_isListening = true;
                    s_isPending   = true;
                }
            }
        /// <summary>
        /// Report session context to WSMan..this will let WSMan send ACK to
        /// client and client can send data.
        /// </summary>
        internal void ReportContext()
        {
            int  result = 0;
            bool isRegisterWaitForSingleObjectFailed = false;

            lock (_syncObject)
            {
                if (isClosed)
                {
                    return;
                }

                if (!isContextReported)
                {
                    isContextReported = true;
                    PSEtwLog.LogAnalyticInformational(PSEventId.ReportContext,
                                                      PSOpcode.Connect, PSTask.None,
                                                      PSKeyword.ManagedPlugin | PSKeyword.UseAlwaysAnalytic,
                                                      creationRequestDetails.ToString(), creationRequestDetails.ToString());

                    // TO BE FIXED - As soon as this API is called, WinRM service will send CommandResponse back and Signal is expected anytime
                    // If Signal comes and executes before registering the notification handle, cleanup will be messed
                    result = WSManNativeApi.WSManPluginReportContext(creationRequestDetails.unmanagedHandle, 0, creationRequestDetails.unmanagedHandle);
                    if (Platform.IsWindows && (WSManPluginConstants.ExitCodeSuccess == result))
                    {
                        registeredShutdownNotification = 1;

                        // Wrap the provided handle so it can be passed to the registration function
                        SafeWaitHandle  safeWaitHandle  = new SafeWaitHandle(creationRequestDetails.shutdownNotificationHandle, false); // Owned by WinRM
                        EventWaitHandle eventWaitHandle = new EventWaitHandle(false, EventResetMode.AutoReset);
                        eventWaitHandle.SafeWaitHandle = safeWaitHandle;

                        // Register shutdown notification handle
                        this.registeredShutDownWaitHandle = ThreadPool.RegisterWaitForSingleObject(
                            eventWaitHandle,
                            new WaitOrTimerCallback(WSManPluginManagedEntryWrapper.PSPluginOperationShutdownCallback),
                            shutDownContext,
                            -1,    // INFINITE
                            true); // TODO: Do I need to worry not being able to set missing WT_TRANSFER_IMPERSONATION?
                        if (this.registeredShutDownWaitHandle == null)
                        {
                            isRegisterWaitForSingleObjectFailed = true;
                            registeredShutdownNotification      = 0;
                        }
                    }
                }
            }

            if ((WSManPluginConstants.ExitCodeSuccess != result) || (isRegisterWaitForSingleObjectFailed))
            {
                string errorMessage;
                if (isRegisterWaitForSingleObjectFailed)
                {
                    errorMessage = StringUtil.Format(RemotingErrorIdStrings.WSManPluginShutdownRegistrationFailed);
                }
                else
                {
                    errorMessage = StringUtil.Format(RemotingErrorIdStrings.WSManPluginReportContextFailed);
                }

                // Report error and close the session
                Exception mgdException = new InvalidOperationException(errorMessage);
                Close(mgdException);
            }
        }
        internal void PrinterNotifyWaitCallback(object state, bool timedOut)
        {
            if (_printerHandle == IntPtr.Zero)
            {
                return;
            }


            _notifyOptions.Count = 1;
            int  pdwChange   = 0;
            var  pNotifyInfo = IntPtr.Zero;
            bool bResult     = FindNextPrinterChangeNotification(_changeHandle, out pdwChange, _notifyOptions,
                                                                 ref pNotifyInfo);

            if (bResult == false || pNotifyInfo == IntPtr.Zero)
            {
                return;
            }


            bool bJobRelatedChange = (pdwChange & PRINTER_CHANGES.PRINTER_CHANGE_ADD_JOB) ==
                                     PRINTER_CHANGES.PRINTER_CHANGE_ADD_JOB ||
                                     (pdwChange & PRINTER_CHANGES.PRINTER_CHANGE_SET_JOB) ==
                                     PRINTER_CHANGES.PRINTER_CHANGE_SET_JOB ||
                                     (pdwChange & PRINTER_CHANGES.PRINTER_CHANGE_DELETE_JOB) ==
                                     PRINTER_CHANGES.PRINTER_CHANGE_DELETE_JOB ||
                                     (pdwChange & PRINTER_CHANGES.PRINTER_CHANGE_WRITE_JOB) ==
                                     PRINTER_CHANGES.PRINTER_CHANGE_WRITE_JOB;

            if (!bJobRelatedChange)
            {
                return;
            }


            var  info  = (PRINTER_NOTIFY_INFO)Marshal.PtrToStructure(pNotifyInfo, typeof(PRINTER_NOTIFY_INFO));
            long pData = (long)pNotifyInfo + (long)Marshal.OffsetOf(typeof(PRINTER_NOTIFY_INFO), "aData");
            var  data  = new PRINTER_NOTIFY_INFO_DATA[info.Count];

            for (uint i = 0; i < info.Count; i++)
            {
                data[i] =
                    (PRINTER_NOTIFY_INFO_DATA)Marshal.PtrToStructure((IntPtr)pData, typeof(PRINTER_NOTIFY_INFO_DATA));
                pData += Marshal.SizeOf(typeof(PRINTER_NOTIFY_INFO_DATA));
            }


            for (int i = 0; i < data.Count(); i++)
            {
                if (data[i].Field == (ushort)PRINTERJOBNOTIFICATIONTYPES.JOB_NOTIFY_FIELD_STATUS &&
                    data[i].Type == (ushort)PRINTERNOTIFICATIONTYPES.JOB_NOTIFY_TYPE
                    )
                {
                    var                jStatus  = (JOBSTATUS)Enum.Parse(typeof(JOBSTATUS), data[i].NotifyData.Data.cbBuf.ToString());
                    int                intJobId = (int)data[i].Id;
                    string             strJobName;
                    PrintSystemJobInfo pji = null;
                    try
                    {
                        _spooler = new PrintQueue(new PrintServer(), SpoolerName);
                        pji      = _spooler.GetJob(intJobId);
                        if (!_objJobDict.ContainsKey(intJobId))
                        {
                            _objJobDict[intJobId] = pji.Name;
                        }

                        strJobName = pji.Name;
                    }
                    catch
                    {
                        //Trace.WriteLine(ex.Message);
                        pji = null;
                        _objJobDict.TryGetValue(intJobId, out strJobName);
                        if (strJobName == null)
                        {
                            strJobName = string.Empty;
                        }
                    }

                    if (OnJobStatusChange != null)
                    {
                        //Let us raise the event
                        OnJobStatusChange(this, new PrintJobChangeEventArgs(intJobId, strJobName, jStatus, pji));
                    }
                }
            }


            _mrEvent.Reset();
            _waitHandle =
                ThreadPool.RegisterWaitForSingleObject(_mrEvent, PrinterNotifyWaitCallback, _mrEvent, -1, true);
        }
示例#9
0
        // Any exceptions that escape synchronously will be caught by the caller and wrapped in a PingException.
        // We do not need to or want to capture such exceptions into the returned task.
        private Task <PingReply> SendPingAsyncCore(IPAddress address, byte[] buffer, int timeout, PingOptions options)
        {
            var tcs = new TaskCompletionSource <PingReply>();

            _taskCompletionSource = tcs;

            _ipv6     = (address.AddressFamily == AddressFamily.InterNetworkV6);
            _sendSize = buffer.Length;

            // Get and cache correct handle.
            if (!_ipv6 && _handlePingV4 == null)
            {
                _handlePingV4 = Interop.IpHlpApi.IcmpCreateFile();
                if (_handlePingV4.IsInvalid)
                {
                    _handlePingV4 = null;
                    throw new Win32Exception(); // Gets last error.
                }
            }
            else if (_ipv6 && _handlePingV6 == null)
            {
                _handlePingV6 = Interop.IpHlpApi.Icmp6CreateFile();
                if (_handlePingV6.IsInvalid)
                {
                    _handlePingV6 = null;
                    throw new Win32Exception(); // Gets last error.
                }
            }

            var ipOptions = new Interop.IpHlpApi.IPOptions(options);

            if (_replyBuffer == null)
            {
                _replyBuffer = SafeLocalAllocHandle.LocalAlloc(MaxUdpPacket);
            }

            // Queue the event.
            int error;

            try
            {
                if (_pingEvent == null)
                {
                    _pingEvent = new ManualResetEvent(false);
                }
                else
                {
                    _pingEvent.Reset();
                }

                _registeredWait = ThreadPool.RegisterWaitForSingleObject(_pingEvent, (state, _) => ((Ping)state).PingCallback(), this, -1, true);

                SetUnmanagedStructures(buffer);

                if (!_ipv6)
                {
                    SafeWaitHandle pingEventSafeWaitHandle = _pingEvent.GetSafeWaitHandle();
                    error = (int)Interop.IpHlpApi.IcmpSendEcho2(
                        _handlePingV4,
                        pingEventSafeWaitHandle,
                        IntPtr.Zero,
                        IntPtr.Zero,
#pragma warning disable CS0618 // Address is marked obsolete
                        (uint)address.Address,
#pragma warning restore CS0618
                        _requestBuffer,
                        (ushort)buffer.Length,
                        ref ipOptions,
                        _replyBuffer,
                        MaxUdpPacket,
                        (uint)timeout);
                }
                else
                {
                    IPEndPoint ep = new IPEndPoint(address, 0);
                    Internals.SocketAddress remoteAddr = IPEndPointExtensions.Serialize(ep);
                    byte[] sourceAddr = new byte[28];

                    SafeWaitHandle pingEventSafeWaitHandle = _pingEvent.GetSafeWaitHandle();
                    error = (int)Interop.IpHlpApi.Icmp6SendEcho2(
                        _handlePingV6,
                        pingEventSafeWaitHandle,
                        IntPtr.Zero,
                        IntPtr.Zero,
                        sourceAddr,
                        remoteAddr.Buffer,
                        _requestBuffer,
                        (ushort)buffer.Length,
                        ref ipOptions,
                        _replyBuffer,
                        MaxUdpPacket,
                        (uint)timeout);
                }
            }
            catch
            {
                UnregisterWaitHandle();
                throw;
            }

            if (error == 0)
            {
                error = Marshal.GetLastWin32Error();

                // Only skip Async IO Pending error value.
                if (error != Interop.IpHlpApi.ERROR_IO_PENDING)
                {
                    // Cleanup.
                    FreeUnmanagedStructures();
                    UnregisterWaitHandle();

                    throw new Win32Exception(error);
                }
            }

            return(tcs.Task);
        }
示例#10
0
文件: Do.cs 项目: benlesh/ALE
 public TimeoutKillswitch(RegisteredWaitHandle regWait, WaitHandle wait)
 {
     RegisteredWaitHandle = regWait;
     WaitHandle           = wait;
 }
        private void AddObjectChangedEvent(EventHandler <ObjectChangedEventArgs> callback)
        {
            //
            // Register a wait handle if one has not been registered already
            //

            Logging.P2PTraceSource.TraceEvent(TraceEventType.Information, 0, "AddObjectChanged() called.");

            lock (LockObjChangedEvent){
                if (m_objectChanged == null)
                {
                    if (m_id.Equals(Guid.Empty))
                    {
                        throw (new PeerToPeerException(SR.GetString(SR.Collab_EmptyGuidError)));
                    }

                    m_objChangedEvent = new AutoResetEvent(false);

                    //
                    // Register callback with a wait handle
                    //

                    m_regObjChangedWaitHandle = ThreadPool.RegisterWaitForSingleObject(m_objChangedEvent,                              //Event that triggers the callback
                                                                                       new WaitOrTimerCallback(ObjectChangedCallback), //callback to be called
                                                                                       null,                                           //state to be passed
                                                                                       -1,                                             //Timeout - aplicable only for timers
                                                                                       false                                           //call us everytime the event is set
                                                                                       );
                    PEER_COLLAB_EVENT_REGISTRATION pcer = new PEER_COLLAB_EVENT_REGISTRATION();
                    pcer.eventType = PeerCollabEventType.EndPointObjectChanged;

                    GUID     guid       = CollaborationHelperFunctions.ConvertGuidToGUID(m_id);
                    GCHandle guidHandle = GCHandle.Alloc(guid, GCHandleType.Pinned);

                    //
                    // Register event with collab
                    //

                    pcer.pInstance = guidHandle.AddrOfPinnedObject();
                    try{
                        int errorCode = UnsafeCollabNativeMethods.PeerCollabRegisterEvent(
                            m_objChangedEvent.SafeWaitHandle,
                            1,
                            ref pcer,
                            out m_safeObjChangedEvent);
                        if (errorCode != 0)
                        {
                            Logging.P2PTraceSource.TraceEvent(TraceEventType.Error, 0, "PeerCollabRegisterEvent returned with errorcode {0}", errorCode);
                            throw PeerToPeerException.CreateFromHr(SR.GetString(SR.Collab_ObjectChangedRegFailed), errorCode);
                        }
                    }
                    finally{
                        if (guidHandle.IsAllocated)
                        {
                            guidHandle.Free();
                        }
                    }
                }
                m_objectChanged += callback;
            }

            Logging.P2PTraceSource.TraceEvent(TraceEventType.Information, 0, "AddObjectChanged() successful.");
        }
示例#12
0
文件: baiduSJPL.cs 项目: zhangvs/-
        private void button1_Click(object sender, EventArgs e)
        {
            var filePath = "";

            if (!File.Exists(txtFileName.Text))
            {
                MessageBox.Show("文件不存在。");
                return;
            }
            else if (textBox2.Text == "")
            {
                MessageBox.Show("城市不能为空。");
                return;
            }
            else
            {
                filePath = openFileDialog1.FileName;//txtFileName.Text;
                //读取excel
                IWorkbook ssfworkbook;
                using (FileStream file = new FileStream(filePath, FileMode.Open, FileAccess.Read))
                {
                    var fileExtension = Path.GetExtension(filePath);
                    if (fileExtension == ".xls")
                    {
                        ssfworkbook            = new HSSFWorkbook(file);
                        StringHelp.filePathOut = filePath.Substring(0, filePath.Length - 4) + "_baidu手机批量检索结果_" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + ".xls";
                        StringHelp.pathError   = filePath.Substring(0, filePath.Length - 5) + "_baidu手机批量执行日志_" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + ".txt";
                    }
                    else if (fileExtension == ".xlsx")
                    {
                        ssfworkbook            = new XSSFWorkbook(file);
                        StringHelp.filePathOut = filePath.Substring(0, filePath.Length - 5) + "_baidu手机批量检索结果_" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + ".xls";
                        StringHelp.pathError   = filePath.Substring(0, filePath.Length - 5) + "_baidu手机批量执行日志_" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + ".txt";
                    }
                    else
                    {
                        MessageBox.Show("文件类型不支持");
                        return;
                    }
                }
                StringHelp.CreateExcel();
                //for (int i = 0; i < ssfworkbook.NumberOfSheets; i++)//遍历薄
                //{
                var sheet = ssfworkbook.GetSheetAt(0);
                dt = DateTime.Now;
                int daoNum = sheet.LastRowNum + 1;
                label3.Text = "导入" + daoNum + "个号码。";
                label4.Text = dt + "正在采集……";

                ThreadPool.SetMaxThreads(4, 4);  //设置最大线程数
                List <Thread> arr = new List <Thread>();
                for (int j = 0; j < daoNum; j++) //LastRowNum 获取的是最后一行的编号(编号从0开始)。getPhysicalNumberOfRows()获取的是物理行数,也就是不包括那些空行(隔行)的情况。
                {
                    var row = sheet.GetRow(j);   //读取当前行数据
                    if (row.GetCell(0).ToString() != "")
                    {
                        ThreadPool.QueueUserWorkItem(new WaitCallback(mainWhile), row.GetCell(0).ToString());
                    }
                }
                //}
            }

            rhw = ThreadPool.RegisterWaitForSingleObject(new System.Threading.AutoResetEvent(false), CheckThreadPool, null, 10000, false);
        }
示例#13
0
        /// <summary>
        /// Creates a task that will complete after a time delay.
        /// </summary>
        /// <remarks>
        /// <para>If the cancellation token is signaled before the specified time delay, then the task
        /// is completed in <see cref="TaskStatus.Canceled"/> state. Otherwise, the task is
        /// completed in <see cref="TaskStatus.RanToCompletion"/> state once the specified time
        /// delay has expired.</para>
        /// <para>This method ignores any fractional milliseconds when evaluating <paramref name="delay"/>.</para>
        /// </remarks>
        /// <param name="delay">The time span to wait before completing the returned task</param>
        /// <param name="cancellationToken">The cancellation token that will be checked prior to completing the returned task</param>
        /// <returns>A task that represents the time delay</returns>
        /// <exception cref="ArgumentOutOfRangeException">If <paramref name="delay"/> represents a negative time interval.</exception>
        /// <exception cref="TaskCanceledException">If the task has been canceled.</exception>
        /// <exception cref="ObjectDisposedException">If the provided <paramref name="cancellationToken"/> has already been disposed.</exception>
        public static Task Delay(TimeSpan delay, CancellationToken cancellationToken)
        {
#if NET45PLUS
            return(Task.Delay(delay, cancellationToken));
#else
            long totalMilliseconds = (long)delay.TotalMilliseconds;
            if (totalMilliseconds < 0)
            {
                throw new ArgumentOutOfRangeException("delay");
            }

            if (cancellationToken.IsCancellationRequested)
            {
                return(CompletedTask.Canceled());
            }

            if (totalMilliseconds == 0)
            {
                return(CompletedTask.Default);
            }

            TaskCompletionSource <VoidResult> result = new TaskCompletionSource <VoidResult>();

#if !PORTABLE
            TaskCompletionSource <VoidResult> intermediateResult = new TaskCompletionSource <VoidResult>();

            RegisteredWaitHandle timerRegisteredWaitHandle        = null;
            RegisteredWaitHandle cancellationRegisteredWaitHandle = null;

            WaitOrTimerCallback timedOutCallback =
                (object state, bool timedOut) =>
            {
                if (timedOut)
                {
                    intermediateResult.TrySetResult(default(VoidResult));
                }
            };

            IAsyncResult asyncResult = intermediateResult.Task;
            timerRegisteredWaitHandle = ThreadPool.RegisterWaitForSingleObject(asyncResult.AsyncWaitHandle, timedOutCallback, null, delay, true);

            if (cancellationToken.CanBeCanceled)
            {
                WaitOrTimerCallback cancelledCallback =
                    (object state, bool timedOut) =>
                {
                    if (cancellationToken.IsCancellationRequested)
                    {
                        intermediateResult.TrySetCanceled();
                    }
                };

                cancellationRegisteredWaitHandle = ThreadPool.RegisterWaitForSingleObject(cancellationToken.WaitHandle, cancelledCallback, null, Timeout.Infinite, true);
            }

            intermediateResult.Task
            .ContinueWith(
                _ =>
            {
                if (cancellationRegisteredWaitHandle != null)
                {
                    cancellationRegisteredWaitHandle.Unregister(null);
                }

                if (timerRegisteredWaitHandle != null)
                {
                    timerRegisteredWaitHandle.Unregister(null);
                }
            }, TaskContinuationOptions.ExecuteSynchronously)
            .ContinueWith(
                cleanupTask =>
            {
                switch (cleanupTask.Status)
                {
                case TaskStatus.RanToCompletion:
                    result.SetFromTask(intermediateResult.Task);
                    break;

                case TaskStatus.Canceled:
                    result.SetCanceled();
                    break;

                case TaskStatus.Faulted:
                    result.SetException(cleanupTask.Exception.InnerExceptions);
                    break;

                default:
                    throw new InvalidOperationException("Unreachable");
                }
            });
#else
            // Since portable-net40 doesn't provide Task.Delay and also doesn't provide ThreadPool.RegisterWaitForSingleObject,
            // we need to implement this functionality using timers stored in a ConditionalWeakTable, which are associated with
            // the actual Task instance that gets returned by this method.

            CancellationTokenRegistration cancellationTokenRegistration = default(CancellationTokenRegistration);
            Timer timer = null;

            TimerCallback timerCallback =
                state =>
            {
                result.TrySetResult(default(VoidResult));
                timer.Dispose();
                cancellationTokenRegistration.Dispose();
            };

            timer = new Timer(timerCallback, null, Timeout.Infinite, Timeout.Infinite);
            _delayTimers.Add(result.Task, timer);
            timer.Change(delay, TimeSpan.FromMilliseconds(-1));


            if (cancellationToken.CanBeCanceled)
            {
                Action cancellationCallback =
                    () =>
                {
                    result.TrySetCanceled();

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

                    cancellationTokenRegistration.Dispose();
                };

                cancellationTokenRegistration = cancellationToken.Register(cancellationCallback);
            }
#endif

            return(result.Task);
#endif
        }
        private void HandleTimer(Object State, bool TimedOut)
        {
            // SWC 20130122 Fix ObjectDisposedException
            if (mre == null)
            {
                System.Reflection.MethodBase method =
                    System.Reflection.MethodInfo.GetCurrentMethod();
                OpenSource.Utilities.EventLogger.Log(
                    this,
                    System.Diagnostics.EventLogEntryType.Error,
                    String.Format(
                        "{0}.{1}() EH called on disposed object",
                        method.DeclaringType.Name,
                        method.Name));
                return;
            }

            if (TimedOut == false)
            {
                return;
            }

            lock (RegLock)
            {
                // SWC 20130122 Fix ObjectDisposedException
                if (mre == null)                                        // Object disposed
                {
                    System.Reflection.MethodBase method =
                        System.Reflection.MethodInfo.GetCurrentMethod();
                    OpenSource.Utilities.EventLogger.Log(
                        this,
                        System.Diagnostics.EventLogEntryType.Error,
                        String.Format(
                            "{0}.{1}() msg01 Object disposed while executing",
                            method.DeclaringType.Name,
                            method.Name));
                    return;
                }
                if (handle != null)
                {
                    handle.Unregister(null);
                    handle = null;
                }
                WaitFlag  = true;
                StartFlag = false;
                // SWC 20130227 Fix high cpu problem
                // SWC Move assignment closer to actual usage
                //timeout = Interval;
            }

            this.ElapsedWeakEvent.Fire();

            // SWC 20130122 Lock down the entire code block
            lock (RegLock)
            {
                // SWC 20130122 Fix ObjectDisposedException
                if (mre == null)                                        // Object disposed
                {
                    System.Reflection.MethodBase method =
                        System.Reflection.MethodInfo.GetCurrentMethod();
                    OpenSource.Utilities.EventLogger.Log(
                        this,
                        System.Diagnostics.EventLogEntryType.Error,
                        String.Format(
                            "{0}.{1}() msg02 Object disposed while executing",
                            method.DeclaringType.Name,
                            method.Name));
                    return;
                }
                if (AutoReset == true)
                {
                    mre.Reset();
                    // SWC 20130227 Fix high cpu problem
                    // SWC Validate Interval setting, assign to timeout for use in callback timer
                    //handle = ThreadPool.RegisterWaitForSingleObject(mre, WOTcb, null, Interval, true);
                    timeout = Math.Max(MINIMUM_INTERVAL, Interval);
                    handle  = ThreadPool.RegisterWaitForSingleObject(mre, WOTcb, null, timeout, true);
                }
                else
                {
                    if (WaitFlag == true && StartFlag == true)
                    {
                        // SWC 20130227 Fix high cpu problem
                        // SWC Move assignment closer to actual usage
                        //Interval = timeout;
                        mre.Reset();
                        if (handle != null)
                        {
                            handle.Unregister(null);
                        }
                        // SWC 20130227 Fix high cpu problem
                        // SWC Conditionally assign validated Interval setting to timeout for use in callback timer
                        //handle = ThreadPool.RegisterWaitForSingleObject(mre, WOTcb, null, Interval, true);
                        handle = ThreadPool.RegisterWaitForSingleObject(mre, WOTcb, null, timeout, true);
                        // SWC Reset timeout to max value for use in next execution
                        timeout = Int32.MaxValue;
                    }
                    WaitFlag  = false;
                    StartFlag = false;
                }
            }
        }
示例#15
0
 private void RegisterTimeOut(WaitHandle handle)
 {
     m_waihandle          = handle;
     m_registerwaithandle =
         ThreadPool.RegisterWaitForSingleObject(handle, TimeOutCallback, m_httpwebrequest, TIMEOUT_TIME, true);
 }
示例#16
0
        public void SendRequest(JsonRpcRequest rpcRequest, int timeout, Action <JsonRpcResponse> callback)
        {
            // Console.WriteLine("发送请求11111111111111"+DateTime.Now.ToShortDateString());
            TracingManager.Info(
                delegate()
            {
                string module = null;
                string action = null;
                if (rpcRequest.Header != null)
                {
                    module = rpcRequest.Header["UU-REQUEST-MODULE"] == null ? "" : rpcRequest.Header["UU-REQUEST-MODULE"];
                    action = rpcRequest.Header["UU-REQUEST-ACTION"] == null ? "" : rpcRequest.Header["UU-REQUEST-ACTION"];
                }
                _tracing.Info(string.Format("jsonrpc request:uri={0} module={1} action={2}\r\nrequestbody:{3}",
                                            rpcRequest.ServiceUri, module, action, rpcRequest.ReqBody));
            }
                );
            _sericeUri = rpcRequest.ServiceUri;
            _callback  = callback;

            _webRequest             = HttpWebRequest.Create(new Uri(_sericeUri));
            _webRequest.Method      = "POST";
            _webRequest.Proxy       = null;
            _webRequest.ContentType = "application/json";
            _webRequest.Headers.Add(HttpRequestHeader.From, rpcRequest.FromComputer);
            _webRequest.Headers.Add(HttpRequestHeader.Pragma, rpcRequest.FromService);

            if (rpcRequest.Header != null && rpcRequest.Header.Count > 0)
            {
                foreach (string key in rpcRequest.Header.AllKeys)
                {
                    _webRequest.Headers.Add(key, rpcRequest.Header[key]);
                }
            }

            byte[] buffer = null;
            if (rpcRequest.ReqBody == null)
            {
                _webRequest.ContentLength = 0;
            }
            else
            {
                buffer = Encoding.UTF8.GetBytes(rpcRequest.ReqBody);//Request.BodyBuffer.GetByteArray();
                _webRequest.ContentLength = buffer.Length;
            }

            timeout = timeout > 0 ? timeout : _timeOut;

            if (timeout > 0)
            {
                _waitHandle       = new ManualResetEvent(false);
                _registeredHandle = ThreadPool.RegisterWaitForSingleObject(_waitHandle, new WaitOrTimerCallback(TimeoutCallback), this, timeout, true);
            }
            if (_webRequest.ContentLength == 0)
            {
                _webRequest.BeginGetResponse(new AsyncCallback(ResponseCallback), this);
            }
            else
            {
                _webRequest.BeginGetRequestStream(
                    delegate(IAsyncResult asyncResult)
                {
                    JsonRpcHttpClientTransaction trans = (JsonRpcHttpClientTransaction)asyncResult.AsyncState;
                    try
                    {
                        WebRequest webReq = trans._webRequest;

                        Stream stream = webReq.EndGetRequestStream(asyncResult);
                        stream.Write(buffer, 0, buffer.Length);
                        stream.Close();
                        webReq.BeginGetResponse(new AsyncCallback(ResponseCallback), this);
                    }
                    catch (Exception ex)
                    {
                        var rpcResonse = new JsonRpcResponse(JsonRpcErrorCode.SendFailed, null, new JsonRpcException(_sericeUri, "send failed", ex), 0);
                        trans.OnCallback(rpcResonse);
                    }
                },
                    this
                    );
            }
        }
        /// <summary>
        /// Returns a response to an Internet request as an asynchronous operation.
        /// </summary>
        /// <remarks>
        /// This operation will not block. The returned <see cref="Task{TResult}"/> object will
        /// complete after a response to an Internet request is available.
        /// </remarks>
        /// <param name="request">The request.</param>
        /// <param name="cancellationToken">The <see cref="CancellationToken"/> that will be assigned to the new <see cref="Task"/>.</param>
        /// <returns>A <see cref="Task"/> object which represents the asynchronous operation.</returns>
        /// <exception cref="ArgumentNullException">If <paramref name="request"/> is <see langword="null"/>.</exception>
        /// <exception cref="WebException">
        /// If <see cref="WebRequest.Abort"/> was previously called.
        /// <para>-or-</para>
        /// <para>If the timeout period for the request expired.</para>
        /// <para>-or-</para>
        /// <para>If an error occurred while processing the request.</para>
        /// </exception>
        public static Task <WebResponse> GetResponseAsync(this WebRequest request, CancellationToken cancellationToken)
        {
            if (request == null)
            {
                throw new ArgumentNullException("request");
            }

            bool timeout = false;
            TaskCompletionSource <WebResponse> completionSource = new TaskCompletionSource <WebResponse>();

            RegisteredWaitHandle timerRegisteredWaitHandle        = null;
            RegisteredWaitHandle cancellationRegisteredWaitHandle = null;
            AsyncCallback        completedCallback =
                result =>
            {
                try
                {
                    if (cancellationRegisteredWaitHandle != null)
                    {
                        cancellationRegisteredWaitHandle.Unregister(null);
                    }

                    if (timerRegisteredWaitHandle != null)
                    {
                        timerRegisteredWaitHandle.Unregister(null);
                    }

                    completionSource.TrySetResult(request.EndGetResponse(result));
                }
                catch (WebException ex)
                {
                    if (timeout)
                    {
                        completionSource.TrySetException(new WebException("No response was received during the time-out period for a request.", WebExceptionStatus.Timeout));
                    }
                    else if (cancellationToken.IsCancellationRequested)
                    {
                        completionSource.TrySetCanceled();
                    }
                    else
                    {
                        completionSource.TrySetException(ex);
                    }
                }
                catch (Exception ex)
                {
                    completionSource.TrySetException(ex);
                }
            };

            IAsyncResult asyncResult = request.BeginGetResponse(completedCallback, null);

            if (!asyncResult.IsCompleted)
            {
                if (request.Timeout != Timeout.Infinite)
                {
                    WaitOrTimerCallback timedOutCallback =
                        (object state, bool timedOut) =>
                    {
                        if (timedOut)
                        {
                            timeout = true;
                            request.Abort();
                        }
                    };

                    timerRegisteredWaitHandle = ThreadPool.RegisterWaitForSingleObject(asyncResult.AsyncWaitHandle, timedOutCallback, null, request.Timeout, true);
                }

                if (cancellationToken.CanBeCanceled)
                {
                    WaitOrTimerCallback cancelledCallback =
                        (object state, bool timedOut) =>
                    {
                        if (cancellationToken.IsCancellationRequested)
                        {
                            request.Abort();
                        }
                    };

                    cancellationRegisteredWaitHandle = ThreadPool.RegisterWaitForSingleObject(cancellationToken.WaitHandle, cancelledCallback, null, Timeout.Infinite, true);
                }
            }

            return(completionSource.Task);
        }
示例#18
0
        /// <summary>
        /// Lancement de l'action
        /// </summary>
        public GenericTesterResult Start()
        {
            GenericTesterResult result = new GenericTesterResult();

            //initialisation
            autoWaitHandle = new AutoResetEvent(false);
            _waitLock      = new ManualResetEvent(false);

            try
            {
                Trace.WriteInfo("Start Action");
                //Enregitrements des instances de fonction de la classe aux événement Econf
                Register();

                Console.WriteLine("TimeOut: " + timeOut);
                //Chargement du timer
                timerHandle = ThreadPool.RegisterWaitForSingleObject(autoWaitHandle, new WaitOrTimerCallback(WaitProc), null, timeOut, true);

                //Lancement de l'action
                Action();

                Trace.WriteInfo("Attente de résultat");
                _waitLock.WaitOne();

                //Si le Timer s'est déclenché
                if (status == TestStatus.TimeOut)
                {
                    listMsg.Add("Timer déclenché");
                    status = TestStatus.TimeOut;
                    Trace.WriteInfo("TIMEOUT :" + status);
                    result = new GenericTesterResult(status, listMsg);
                }
                else if (status == TestStatus.Failed || status == TestStatus.Unknown)
                {
                    Trace.WriteInfo("ECHEC :" + status);
                    result = new GenericTesterResult(status, listMsg);
                }
                else
                {
                    if (datas != null)
                    {
                        Trace.WriteInfo("SUCCES : " + status);
                        result = new GenericTesterResult(status, listMsg, datas);
                    }
                    else
                    {
                        result = new GenericTesterResult(status, listMsg);
                    }
                }
            }

            catch (Exception e)
            {
                status = TestStatus.Failed;
                listMsg.Add("Erreur innatendue");
                Trace.WriteError(e.ToString());
                result = new GenericTesterResult(status, listMsg);
            }

            finally
            {
                Trace.WriteInfo("Fin de l'action");
                //Désenregitrements des instances de fonction de la classe aux événement Econf
                Unregister();
                //On désarme le Timer
                timerHandle.Unregister(null);
            }
            return(result);
        }
示例#19
0
 protected override void InternalStart_FromWorkerThread(int delay)
 {
     m_waitObject.Reset();
     m_registeredHandle = ThreadPool.RegisterWaitForSingleObject(m_waitObject, BeginRunOnTimer, null, delay, executeOnlyOnce: true);
 }
        public static Task <bool> ToTask(this WaitHandle handle, int timeout = Timeout.Infinite, CancellationToken cancellationToken = default(CancellationToken))
        {
            Requires.NotNull(handle, nameof(handle));

            // Check whether the handle is already signaled as an optimization.
            // But even for WaitOne(0) the CLR can pump messages if called on the UI thread, which the caller may not
            // be expecting at this time, so be sure there is no message pump active by controlling the SynchronizationContext.
            using (NoMessagePumpSyncContext.Default.Apply())
            {
                if (handle.WaitOne(0))
                {
                    return(TrueTask);
                }
                else if (timeout == 0)
                {
                    return(FalseTask);
                }
            }

            cancellationToken.ThrowIfCancellationRequested();
            var tcs = new TaskCompletionSource <bool>();

            // Arrange that if the caller signals their cancellation token that we complete the task
            // we return immediately. Because of the continuation we've scheduled on that task, this
            // will automatically release the wait handle notification as well.
            CancellationTokenRegistration cancellationRegistration =
                cancellationToken.Register(
                    state =>
            {
                var tuple = (Tuple <TaskCompletionSource <bool>, CancellationToken>)state;
                tuple.Item1.TrySetCanceled(tuple.Item2);
            },
                    Tuple.Create(tcs, cancellationToken));

            RegisteredWaitHandle callbackHandle = ThreadPool.RegisterWaitForSingleObject(
                handle,
                (state, timedOut) => ((TaskCompletionSource <bool>)state).TrySetResult(!timedOut),
                state: tcs,
                millisecondsTimeOutInterval: timeout,
                executeOnlyOnce: true);

            // It's important that we guarantee that when the returned task completes (whether cancelled, timed out, or signaled)
            // that we release all resources.
            if (cancellationToken.CanBeCanceled)
            {
                // We have a cancellation token registration and a wait handle registration to release.
                // Use a tuple as a state object to avoid allocating delegates and closures each time this method is called.
                tcs.Task.ContinueWith(
                    (_, state) =>
                {
                    var tuple = (Tuple <RegisteredWaitHandle, CancellationTokenRegistration>)state;
                    tuple.Item1.Unregister(null); // release resources for the async callback
                    tuple.Item2.Dispose();        // release memory for cancellation token registration
                },
                    Tuple.Create <RegisteredWaitHandle, CancellationTokenRegistration>(callbackHandle, cancellationRegistration),
                    CancellationToken.None,
                    TaskContinuationOptions.ExecuteSynchronously,
                    TaskScheduler.Default);
            }
            else
            {
                // Since the cancellation token was the default one, the only thing we need to track is clearing the RegisteredWaitHandle,
                // so do this such that we allocate as few objects as possible.
                tcs.Task.ContinueWith(
                    (_, state) => ((RegisteredWaitHandle)state).Unregister(null),
                    callbackHandle,
                    CancellationToken.None,
                    TaskContinuationOptions.ExecuteSynchronously,
                    TaskScheduler.Default);
            }

            return(tcs.Task);
        }
示例#21
0
 private void RegisterTimeOut(WaitHandle handle)
 {
     m_WaitHandle         = handle;
     m_RegisterWaitHandle = ThreadPool.RegisterWaitForSingleObject(handle, new WaitOrTimerCallback(OnTimeoutCallback), m_Request, TIMEOUT_TIME, true);
 }
示例#22
0
    public static int Main(String [] args)
    {
        int rValue = 100;
        RegisteredWaitHandle rwh = null;

        Console.WriteLine("Test AutoResetEvent for expected NullRef Exceptions");
        Console.WriteLine( );


        try {
            rwh.Equals(new ManualResetEvent(true));
            rValue = 4;
        }
        catch (NullReferenceException) {
            Console.WriteLine("Caught NullReferenceException   (rwh.Equals(new ManualResetEvent()))");
        }

        try {
            rwh.GetHashCode();
            rValue = 5;
        }
        catch (NullReferenceException) {
            Console.WriteLine("Caught NullReferenceException   (rwh.GetHasCode())");
        }

        // try {
        //  rwh.GetLifetimeService();
        //  rValue = 6;
        // }
        // catch (NullReferenceException) {
        //  Console.WriteLine("Caught NullReferenceException   (rwh.GetLifetimeService())");
        // }

        try {
            rwh.GetType();
            rValue = 7;
        }
        catch (NullReferenceException) {
            Console.WriteLine("Caught NullReferenceException   (rwh.GetType())");
        }

        // try {
        //  rwh.InitializeLifetimeService();
        //  rValue = 8;
        // }
        // catch (NullReferenceException) {
        //  Console.WriteLine("Caught NullReferenceException   (rwh.InitializeLifeTimeService())");
        // }

        try {
            rwh.ToString();
            rValue = 11;
        }
        catch (NullReferenceException) {
            Console.WriteLine("Caught NullReferenceException   (rwh.ToString())");
        }

        try {
            rwh.Unregister(new AutoResetEvent(true));
            rValue = 12;
        }
        catch (NullReferenceException) {
            Console.WriteLine("Caught NullReferenceException   (rwh.Unregister())");
        }


        Console.WriteLine("Return Code == {0}", rValue);
        return(rValue);
    }
示例#23
0
        public void PrinterNotifyWaitCallback(Object state, bool timedOut)
        {
            if (_printerHandle == IntPtr.Zero)
            {
                return;
            }
            #region read notification details
            _notifyOptions.Count = 1;
            int    pdwChange   = 0;
            IntPtr pNotifyInfo = IntPtr.Zero;
            bool   bResult     = FindNextPrinterChangeNotification(_changeHandle, out pdwChange, _notifyOptions, out pNotifyInfo);
            //If the Printer Change Notification Call did not give data, exit code
            if ((bResult == false) || (((int)pNotifyInfo) == 0))
            {
                return;
            }

            //If the Change Notification was not relgated to job, exit code
            bool bJobRelatedChange = ((pdwChange & PRINTER_CHANGES.PRINTER_CHANGE_ADD_JOB) == PRINTER_CHANGES.PRINTER_CHANGE_ADD_JOB) ||
                                     ((pdwChange & PRINTER_CHANGES.PRINTER_CHANGE_SET_JOB) == PRINTER_CHANGES.PRINTER_CHANGE_SET_JOB) ||
                                     ((pdwChange & PRINTER_CHANGES.PRINTER_CHANGE_DELETE_JOB) == PRINTER_CHANGES.PRINTER_CHANGE_DELETE_JOB) ||
                                     ((pdwChange & PRINTER_CHANGES.PRINTER_CHANGE_WRITE_JOB) == PRINTER_CHANGES.PRINTER_CHANGE_WRITE_JOB);
            if (!bJobRelatedChange)
            {
                return;
            }
            #endregion

            #region populate Notification Information
            //Now, let us initialize and populate the Notify Info data
            PRINTER_NOTIFY_INFO info = (PRINTER_NOTIFY_INFO)Marshal.PtrToStructure(pNotifyInfo, typeof(PRINTER_NOTIFY_INFO));
            int pData = (int)pNotifyInfo + Marshal.SizeOf(typeof(PRINTER_NOTIFY_INFO));
            PRINTER_NOTIFY_INFO_DATA[] data = new PRINTER_NOTIFY_INFO_DATA[info.Count];
            for (uint i = 0; i < info.Count; i++)
            {
                data[i] = (PRINTER_NOTIFY_INFO_DATA)Marshal.PtrToStructure((IntPtr)pData, typeof(PRINTER_NOTIFY_INFO_DATA));
                pData  += Marshal.SizeOf(typeof(PRINTER_NOTIFY_INFO_DATA));
            }
            #endregion

            #region iterate through all elements in the data array
            for (int i = 0; i < data.Count(); i++)
            {
                if ((data[i].Field == (ushort)PRINTERJOBNOTIFICATIONTYPES.JOB_NOTIFY_FIELD_STATUS) &&
                    (data[i].Type == (ushort)PRINTERNOTIFICATIONTYPES.JOB_NOTIFY_TYPE)
                    )
                {
                    JOBSTATUS          jStatus    = (JOBSTATUS)Enum.Parse(typeof(JOBSTATUS), data[i].NotifyData.Data.cbBuf.ToString());
                    int                intJobID   = (int)data[i].Id;
                    string             strJobName = "";
                    PrintSystemJobInfo pji        = null;
                    try
                    {
                        _spooler = new PrintQueue(new PrintServer(), _spoolerName);
                        pji      = _spooler.GetJob(intJobID);
                        if (!objJobDict.ContainsKey(intJobID))
                        {
                            objJobDict[intJobID] = pji.Name;
                        }
                        strJobName = pji.Name;
                    }
                    catch
                    {
                        pji = null;
                        objJobDict.TryGetValue(intJobID, out strJobName);
                        if (strJobName == null)
                        {
                            strJobName = "";
                        }
                    }

                    if (OnJobStatusChange != null)
                    {
                        //Let us raise the event
                        OnJobStatusChange(this, new PrintJobChangeEventArgs(intJobID, strJobName, jStatus, pji));
                    }
                }
            }
            #endregion

            #region reset the Event and wait for the next event
            _mrEvent.Reset();
            _waitHandle = ThreadPool.RegisterWaitForSingleObject(_mrEvent, new WaitOrTimerCallback(PrinterNotifyWaitCallback), _mrEvent, -1, false);
            #endregion
        }
示例#24
0
 public ThreadPoolRegistration(WaitHandle handle, TimeSpan timeout, TaskCompletionSource <bool> tcs)
 {
     _registeredWaitHandle = ThreadPool.RegisterWaitForSingleObject(handle,
                                                                    (state, timedOut) => ((TaskCompletionSource <bool>)state).TrySetResult(!timedOut), tcs,
                                                                    timeout, executeOnlyOnce: true);
 }
示例#25
0
    private void ReadCallBack(IAsyncResult asyncResult)
    {
        this.myRequestState = (Downloader.RequestState)asyncResult.get_AsyncState();
        Stream streamResponse = this.myRequestState.streamResponse;
        int    num            = streamResponse.EndRead(asyncResult);

        this.myRequestState.read = num;
        try
        {
            if (num > 0)
            {
                this.Result = this.fs.BeginWrite(this.myRequestState.BufferRead, 0, num, new AsyncCallback(this.WriteCallBack), this.myRequestState);
                return;
            }
        }
        catch (Exception ex)
        {
            TimerHeap.DelTimer(this.timeOutTimer);
            if (this.Handle != null)
            {
                this.Handle.Unregister(this.Result.get_AsyncWaitHandle());
                this.Handle = null;
            }
            if (this.ManualHandle)
            {
                return;
            }
            Debug.LogError("ReadCallBack Exception raised!");
            Debug.LogError(ex.ToString());
            if (this.ManualHandle)
            {
                return;
            }
            Loom.Current.QueueOnMainThread(delegate
            {
                this.ExceptionHandle();
            });
            return;
        }
        string md5FilePath = Downloader.GetMd5FilePath(this.fileFullName);

        FileHelper.DeleteIfExist(md5FilePath);
        TimerHeap.DelTimer(this.timeOutTimer);
        long length = this.fs.get_Length();

        this.fs.Dispose();
        if (this.Handle != null)
        {
            this.Handle.Unregister(this.Result.get_AsyncWaitHandle());
        }
        this.myRequestState.response.Close();
        Debug.LogFormat("localFileLen: {0} localFileSize: {1} downloadFileSize: {2}", new object[]
        {
            length,
            this.localFileSize,
            this.downloadFileSize
        });
        if ((long)this.localFileSize == this.downloadFileSize && length == this.downloadFileSize)
        {
            if (++this.downloadFileIndex < this.urls.get_Count())
            {
                Loom.Current.QueueOnMainThread(delegate
                {
                    this.SetDetails();
                });
                this.fs.Close();
                this.retryTime = 0;
                Loom.Current.QueueOnMainThread(delegate
                {
                    this.Download(this.urls.get_Item(this.downloadFileIndex), this.localPaths.get_Item(this.downloadFileIndex));
                });
            }
            else
            {
                this.fs.Close();
                this.allIsFinish = true;
                Loom.Current.QueueOnMainThread(delegate
                {
                    this.DoFinished();
                });
            }
        }
        else
        {
            this.fs.Dispose();
            File.Delete(this.LocalPath);
            this.retryTime = 0;
            Loom.Current.QueueOnMainThread(delegate
            {
                this.Download(this.urls.get_Item(this.downloadFileIndex), this.localPaths.get_Item(this.downloadFileIndex));
            });
        }
    }
示例#26
0
        /// <summary>
        /// Returns a response to an Internet request as an asynchronous operation.
        /// </summary>
        /// <remarks>
        /// <para>This operation will not block. The returned <see cref="Task{TResult}"/> object will
        /// complete after a response to an Internet request is available.</para>
        /// </remarks>
        /// <param name="request">The request.</param>
        /// <param name="throwOnError"><see langword="true"/> to throw a <see cref="WebException"/> if the <see cref="HttpWebResponse.StatusCode"/> of the response is greater than 400; otherwise, <see langword="false"/> to return the <see cref="WebResponse"/> in the result for these cases.</param>
        /// <param name="cancellationToken">The <see cref="CancellationToken"/> that will be assigned to the new <see cref="Task"/>.</param>
        /// <returns>A <see cref="Task"/> object which represents the asynchronous operation.</returns>
        /// <exception cref="ArgumentNullException">
        /// <para>If <paramref name="request"/> is <see langword="null"/>.</para>
        /// </exception>
        /// <exception cref="WebException">
        /// <para>If <see cref="WebRequest.Abort"/> was previously called.</para>
        /// <para>-or-</para>
        /// <para>If the timeout period for the request expired.</para>
        /// <para>-or-</para>
        /// <para>If an error occurred while processing the request.</para>
        /// </exception>
        public static Task <WebResponse> GetResponseAsync(this WebRequest request, bool throwOnError, CancellationToken cancellationToken)
        {
            if (request == null)
            {
                throw new ArgumentNullException("request");
            }

#if PORTABLE
            bool timeout = false;

            CancellationTokenRegistration cancellationTokenRegistration;
            if (cancellationToken.CanBeCanceled)
            {
                Action cancellationAction = request.Abort;
                cancellationTokenRegistration = cancellationToken.Register(cancellationAction);
            }
            else
            {
                cancellationTokenRegistration = default(CancellationTokenRegistration);
            }

            CancellationTokenSource noRequestTimeoutTokenSource = new CancellationTokenSource();
            WebExceptionStatus      timeoutStatus;
            if (!Enum.TryParse("Timeout", out timeoutStatus))
            {
                timeoutStatus = WebExceptionStatus.UnknownError;
            }

            int requestTimeout;
#if NET45PLUS
            try
            {
                // hack to work around PCL limitation in .NET 4.5
                dynamic dynamicRequest = request;
                requestTimeout = dynamicRequest.Timeout;
            }
            catch (RuntimeBinderException)
            {
                requestTimeout = Timeout.Infinite;
            }
#else
            // hack to work around PCL limitation in .NET 4.0
            var propertyInfo = request.GetType().GetProperty("Timeout", typeof(int));
            if (propertyInfo != null)
            {
                requestTimeout = (int)propertyInfo.GetValue(request, null);
            }
            else
            {
                requestTimeout = Timeout.Infinite;
            }
#endif

            if (requestTimeout >= 0)
            {
                Task timeoutTask = DelayedTask.Delay(TimeSpan.FromMilliseconds(requestTimeout), noRequestTimeoutTokenSource.Token).Select(
                    _ =>
                {
                    timeout = true;
                    request.Abort();
                });
            }

            TaskCompletionSource <WebResponse> completionSource = new TaskCompletionSource <WebResponse>();

            AsyncCallback completedCallback =
                result =>
            {
                try
                {
                    noRequestTimeoutTokenSource.Cancel();
                    noRequestTimeoutTokenSource.Dispose();
                    cancellationTokenRegistration.Dispose();
                    completionSource.TrySetResult(request.EndGetResponse(result));
                }
                catch (WebException ex)
                {
                    if (timeout)
                    {
                        completionSource.TrySetException(new WebException("No response was received during the time-out period for a request.", timeoutStatus));
                    }
                    else if (cancellationToken.IsCancellationRequested)
                    {
                        completionSource.TrySetCanceled();
                    }
                    else if (ex.Response != null && !throwOnError)
                    {
                        completionSource.TrySetResult(ex.Response);
                    }
                    else
                    {
                        completionSource.TrySetException(ex);
                    }
                }
                catch (Exception ex)
                {
                    completionSource.TrySetException(ex);
                }
            };

            IAsyncResult asyncResult = request.BeginGetResponse(completedCallback, null);
            return(completionSource.Task);
#else
            bool timeout = false;
            TaskCompletionSource <WebResponse> completionSource = new TaskCompletionSource <WebResponse>();

            RegisteredWaitHandle timerRegisteredWaitHandle        = null;
            RegisteredWaitHandle cancellationRegisteredWaitHandle = null;
            AsyncCallback        completedCallback =
                result =>
            {
                try
                {
                    if (cancellationRegisteredWaitHandle != null)
                    {
                        cancellationRegisteredWaitHandle.Unregister(null);
                    }

                    if (timerRegisteredWaitHandle != null)
                    {
                        timerRegisteredWaitHandle.Unregister(null);
                    }

                    completionSource.TrySetResult(request.EndGetResponse(result));
                }
                catch (WebException ex)
                {
                    if (timeout)
                    {
                        completionSource.TrySetException(new WebException("No response was received during the time-out period for a request.", WebExceptionStatus.Timeout));
                    }
                    else if (cancellationToken.IsCancellationRequested)
                    {
                        completionSource.TrySetCanceled();
                    }
                    else if (ex.Response != null && !throwOnError)
                    {
                        completionSource.TrySetResult(ex.Response);
                    }
                    else
                    {
                        completionSource.TrySetException(ex);
                    }
                }
                catch (Exception ex)
                {
                    completionSource.TrySetException(ex);
                }
            };

            IAsyncResult asyncResult = request.BeginGetResponse(completedCallback, null);
            if (!asyncResult.IsCompleted)
            {
                if (request.Timeout != Timeout.Infinite)
                {
                    WaitOrTimerCallback timedOutCallback =
                        (object state, bool timedOut) =>
                    {
                        if (timedOut)
                        {
                            timeout = true;
                            request.Abort();
                        }
                    };

                    timerRegisteredWaitHandle = ThreadPool.RegisterWaitForSingleObject(asyncResult.AsyncWaitHandle, timedOutCallback, null, request.Timeout, true);
                }

                if (cancellationToken.CanBeCanceled)
                {
                    WaitOrTimerCallback cancelledCallback =
                        (object state, bool timedOut) =>
                    {
                        if (cancellationToken.IsCancellationRequested)
                        {
                            request.Abort();
                        }
                    };

                    cancellationRegisteredWaitHandle = ThreadPool.RegisterWaitForSingleObject(cancellationToken.WaitHandle, cancelledCallback, null, Timeout.Infinite, true);
                }
            }

            return(completionSource.Task);
#endif
        }
示例#27
0
            private static void StartHelper(NetworkAddressChangedEventHandler caller, bool captureContext, StartIPOptions startIPOptions)
            {
                lock (s_callerArray) {
                    // setup changedEvent and native overlapped struct.
                    if (s_ipv4Socket == null)
                    {
                        Socket.InitializeSockets();

                        int blocking;

                        if (Socket.OSSupportsIPv4)
                        {
                            blocking     = -1;
                            s_ipv4Socket = SafeCloseSocketAndEvent.CreateWSASocketWithEvent(AddressFamily.InterNetwork, SocketType.Dgram, (ProtocolType)0, true, false);
                            UnsafeNclNativeMethods.OSSOCK.ioctlsocket(s_ipv4Socket, IoctlSocketConstants.FIONBIO, ref blocking);
                            s_ipv4WaitHandle = s_ipv4Socket.GetEventHandle();
                        }

                        if (Socket.OSSupportsIPv6)
                        {
                            blocking     = -1;
                            s_ipv6Socket = SafeCloseSocketAndEvent.CreateWSASocketWithEvent(AddressFamily.InterNetworkV6, SocketType.Dgram, (ProtocolType)0, true, false);
                            UnsafeNclNativeMethods.OSSOCK.ioctlsocket(s_ipv6Socket, IoctlSocketConstants.FIONBIO, ref blocking);
                            s_ipv6WaitHandle = s_ipv6Socket.GetEventHandle();
                        }
                    }

                    if ((caller != null) && (!s_callerArray.Contains(caller)))
                    {
                        s_callerArray.Add(caller, captureContext ? ExecutionContext.Capture() : null);
                    }

                    //if s_listener is not null, it means we are already actively listening
                    if (s_isListening || s_callerArray.Count == 0)
                    {
                        return;
                    }

                    if (!s_isPending)
                    {
                        int         length;
                        SocketError errorCode;

                        if (Socket.OSSupportsIPv4 && (startIPOptions & StartIPOptions.StartIPv4) != 0)
                        {
                            s_registeredWait = ThreadPool.UnsafeRegisterWaitForSingleObject(
                                s_ipv4WaitHandle,
                                new WaitOrTimerCallback(AddressChangedCallback),
                                StartIPOptions.StartIPv4,
                                -1,
                                true);

                            errorCode = (SocketError)UnsafeNclNativeMethods.OSSOCK.WSAIoctl_Blocking(
                                s_ipv4Socket.DangerousGetHandle(),
                                (int)IOControlCode.AddressListChange,
                                null, 0, null, 0,
                                out length,
                                SafeNativeOverlapped.Zero, IntPtr.Zero);

                            if (errorCode != SocketError.Success)
                            {
                                NetworkInformationException exception = new NetworkInformationException();
                                if (exception.ErrorCode != (uint)SocketError.WouldBlock)
                                {
                                    throw exception;
                                }
                            }

                            errorCode = (SocketError)UnsafeNclNativeMethods.OSSOCK.WSAEventSelect(s_ipv4Socket, s_ipv4Socket.GetEventHandle().SafeWaitHandle, AsyncEventBits.FdAddressListChange);
                            if (errorCode != SocketError.Success)
                            {
                                throw new NetworkInformationException();
                            }
                        }

                        if (Socket.OSSupportsIPv6 && (startIPOptions & StartIPOptions.StartIPv6) != 0)
                        {
                            s_registeredWait = ThreadPool.UnsafeRegisterWaitForSingleObject(
                                s_ipv6WaitHandle,
                                new WaitOrTimerCallback(AddressChangedCallback),
                                StartIPOptions.StartIPv6,
                                -1,
                                true);

                            errorCode = (SocketError)UnsafeNclNativeMethods.OSSOCK.WSAIoctl_Blocking(
                                s_ipv6Socket.DangerousGetHandle(),
                                (int)IOControlCode.AddressListChange,
                                null, 0, null, 0,
                                out length,
                                SafeNativeOverlapped.Zero, IntPtr.Zero);

                            if (errorCode != SocketError.Success)
                            {
                                NetworkInformationException exception = new NetworkInformationException();
                                if (exception.ErrorCode != (uint)SocketError.WouldBlock)
                                {
                                    throw exception;
                                }
                            }

                            errorCode = (SocketError)UnsafeNclNativeMethods.OSSOCK.WSAEventSelect(s_ipv6Socket, s_ipv6Socket.GetEventHandle().SafeWaitHandle, AsyncEventBits.FdAddressListChange);
                            if (errorCode != SocketError.Success)
                            {
                                throw new NetworkInformationException();
                            }
                        }
                    }

                    s_isListening = true;
                    s_isPending   = true;
                }
            }
示例#28
0
        internal bool EnableTransportManagerSendDataToClient(
            WSManNativeApi.WSManPluginRequest requestDetails,
            WSManPluginOperationShutdownContext ctxtToReport)
        {
            _shutDownContext = ctxtToReport;
            bool isRegisterWaitForSingleObjectSucceeded = true;

            lock (_syncObject)
            {
                if (_isRequestPending)
                {
                    // if a request is already pending..ignore this.
                    WSManPluginInstance.ReportWSManOperationComplete(
                        requestDetails,
                        WSManPluginErrorCodes.NoError);
                    return(false);
                }

                if (_isClosed)
                {
                    WSManPluginInstance.ReportWSManOperationComplete(requestDetails, _lastErrorReported);
                    return(false);
                }

                _isRequestPending = true;
                _requestDetails   = requestDetails;

                if (Platform.IsWindows)
                {
                    // Wrap the provided handle so it can be passed to the registration function
                    SafeWaitHandle  safeWaitHandle  = new SafeWaitHandle(requestDetails.shutdownNotificationHandle, false); // Owned by WinRM
                    EventWaitHandle eventWaitHandle = new EventWaitHandle(false, EventResetMode.AutoReset);
                    eventWaitHandle.SafeWaitHandle = safeWaitHandle;

                    _registeredShutDownWaitHandle = ThreadPool.RegisterWaitForSingleObject(
                        eventWaitHandle,
                        new WaitOrTimerCallback(WSManPluginManagedEntryWrapper.PSPluginOperationShutdownCallback),
                        _shutDownContext,
                        -1,     // INFINITE
                        true);  // TODO: Do I need to worry not being able to set missing WT_TRANSFER_IMPERSONATION?
                    if (_registeredShutDownWaitHandle == null)
                    {
                        isRegisterWaitForSingleObjectSucceeded = false;
                    }
                }
                // release thread waiting to send data to the client.
                _waitHandle.Set();
            }

            if (!isRegisterWaitForSingleObjectSucceeded)
            {
                WSManPluginInstance.PerformCloseOperation(ctxtToReport);
                WSManPluginInstance.ReportOperationComplete(
                    requestDetails,
                    WSManPluginErrorCodes.ShutdownRegistrationFailed,
                    StringUtil.Format(
                        RemotingErrorIdStrings.WSManPluginShutdownRegistrationFailed));
                return(false);
            }

            return(true);
        }
        private void btnStart_Click(object sender, EventArgs e)
        {
            btnSearch.Text    = "加载中..";
            btnSearch.Enabled = false;

            string strurlBaidu  = "http://image.baidu.com/i?tn=baiduimage&ipn=r&ct=201326592&cl=2&lm=-1&st=-1&fm=result&fr=&sf=1&fmq=&pv=&ic=0&nc=1&z=&se=1&showtab=0&fb=0&width=&height=&face=0&istype=2&ie=utf-8&word=";
            string strurlQQ     = "http://soso.music.qq.com/fcgi-bin/music_json.fcg?mid=1&catZhida=1&lossless=0&json=1&w=Key&num=30&t=8&p=1&utf8=1&searchid=216648286573551810&remoteplace=sizer.yqqlist.album&g_tk=5381&loginUin=0&hostUin=0&format=yqq&jsonpCallback=MusicJsonCallback&needNewCode=0";
            string strurlGoogle = "http://www.google.com.hk/search?newwindow=1&safe=strict&hl=zh-CN&biw=1366&bih=654&site=imghp&tbm=isch&sa=1&q=";
            string strurl163    = "http://music.163.com/#/m/search?s=key&_page=search&type=10";
            string strurlXiaMi  = "http://www.xiami.com/search?spm=a1z1s.3521873.23310045.1.AKUtUf&key=";
            string strurlSouGou = "http://pic.sogou.com/pics?ie=utf8&p=40230504&interV=kKIOkrELjboMmLkEk7oTkKIMkbELjbgQmLkElbcTkKILmrELjboLmLkEkr4TkKIRmLkEk78TkKILkbELjboN_1861238217&query=";
            string strurl360    = "http://image.so.com/i?ie=utf-8&q=";
            string strurl       = "";

            switch (cobEngine.Text)
            {
            case "BaiDu":
                strurl      = strurlBaidu + txtKeyWord.Text;
                strEngine   = cobEngine.Text;
                SourceCode += GetWebClient(strurl);
                break;

            case "QQ":
                strurl     = strurlQQ.Replace("Key", System.Web.HttpUtility.UrlEncode(txtKeyWord.Text, System.Text.Encoding.GetEncoding("UTF-8")));
                strEngine  = cobEngine.Text;
                SourceCode = GetWebClient(strurl);
                SourceCode = CreateImageUrl(SourceCode);
                break;

            case "Google":
                strurl     = strurlGoogle + txtKeyWord.Text;
                strEngine  = cobEngine.Text;
                SourceCode = GetWebClient(strurl);
                break;

            case "163":
                strEngine  = cobEngine.Text;
                SourceCode = PostData("http://music.163.com/api/search/get/web?csrf_token=", "hlpretag=%3Cspan%20class%3D%22s-fc7%22%3E&hlposttag=%3C%2Fspan%3E&s=" + GuessAlbumNameBy163(txtKeyWord.Text) + "&_page=search&type=10&offset=0&total=true&limit=75", "http://music.163.com");
                break;

            case "XiaMi":
                strurl     = strurlXiaMi + txtKeyWord.Text;
                strEngine  = cobEngine.Text;
                SourceCode = GetWebClient(strurl);
                break;

            case "SouGou":
                strurl     = strurlSouGou + txtKeyWord.Text;
                strEngine  = cobEngine.Text;
                SourceCode = GetWebClient(strurl);
                break;

            case "360":
                strurl     = strurl360 + txtKeyWord.Text;
                strEngine  = cobEngine.Text;
                SourceCode = GetWebClient(strurl);
                break;

            default:
                break;
            }


            flpPicture.Controls.Clear();
            httpList = GetHyperLinks(SourceCode);
            iThread  = 10;
            int iSum = httpList.Count;
            int iAve = iSum / iThread;
            int iMod = iSum % iThread;

            try
            {
                for (int i = 0; i < iThread; i++)
                {
                    ThreadInfo ti = new ThreadInfo();
                    if (i == 0)
                    {
                        ti.iStart = 0;
                        ti.iEnd   = iAve - 1;
                    }

                    else
                    {
                        ti.iStart = i * iAve;
                        ti.iEnd   = (i * iAve) + iAve - 1;
                    }
                    ThreadPool.QueueUserWorkItem(new WaitCallback(Mp3AlbumCoverUpdaterToForm), ti);
                }
                if (iMod != 0)
                {
                    ThreadInfo ti = new ThreadInfo();
                    ti.iStart = iAve * iThread;
                    ti.iEnd   = iSum - 1;
                    ThreadPool.QueueUserWorkItem(new WaitCallback(Mp3AlbumCoverUpdaterToForm), ti);
                }
                //AutoResetEvent mainAutoResetEvent = new AutoResetEvent(false);
                registeredWaitHandle = ThreadPool.RegisterWaitForSingleObject(new AutoResetEvent(false), new WaitOrTimerCallback(delegate(object obj, bool timeout)
                {
                    int workerThreads  = 0;
                    int maxWordThreads = 0;
                    int compleThreads  = 0;
                    ThreadPool.GetAvailableThreads(out workerThreads, out compleThreads);
                    ThreadPool.GetMaxThreads(out maxWordThreads, out compleThreads);
                    if (workerThreads == maxWordThreads)
                    {
                        //mainAutoResetEvent.Set();
                        registeredWaitHandle.Unregister(null);
                        btnSearch.Invoke(new ChangeControlEnable(ChangeButtonEnable), new object[] { btnSearch });
                    }
                }), null, 1000, false);
                //mainAutoResetEvent.WaitOne();

                this.Cursor = Cursors.WaitCursor;
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                this.Cursor = Cursors.Default;
            }
        }
示例#30
0
        internal void DoClose(
            bool isShuttingDown,
            Exception reasonForClose)
        {
            if (_isClosed)
            {
                return;
            }

            lock (_syncObject)
            {
                if (_isClosed)
                {
                    return;
                }

                _isClosed          = true;
                _lastErrorReported = reasonForClose;

                if (!_isRequestPending)
                {
                    // release threads blocked on the sending data to client if any
                    _waitHandle.Set();
                }
            }

            // only one thread will reach here

            // let everyone know that we are about to close
            try
            {
                RaiseClosingEvent();

                foreach (var cmdTransportKvp in _activeCmdTransportManagers)
                {
                    cmdTransportKvp.Value.Close(reasonForClose);
                }

                _activeCmdTransportManagers.Clear();

                if (_registeredShutDownWaitHandle != null)
                {
                    // This will not wait for the callback to complete.
                    _registeredShutDownWaitHandle.Unregister(null);
                    _registeredShutDownWaitHandle = null;
                }

                // Delete the context only if isShuttingDown != true. isShuttingDown will
                // be true only when the method is called from RegisterWaitForSingleObject
                // handler..in which case the context will be freed from the callback.
                if (_shutDownContext != null)
                {
                    _shutDownContext = null;
                }

                // This might happen when client did not send a receive request
                // but the server is closing
                if (_requestDetails != null)
                {
                    // Notify that no more data is being sent on this transport.
                    WSManNativeApi.WSManPluginReceiveResult(
                        _requestDetails.unmanagedHandle,
                        (int)WSManNativeApi.WSManFlagReceive.WSMAN_FLAG_RECEIVE_RESULT_NO_MORE_DATA,
                        WSManPluginConstants.SupportedOutputStream,
                        IntPtr.Zero,
                        WSManNativeApi.WSMAN_COMMAND_STATE_DONE,
                        0);

                    WSManPluginInstance.ReportWSManOperationComplete(_requestDetails, reasonForClose);
                    // We should not use request details again after reporting operation complete
                    // so releasing the resource. Remember not to free this memory as this memory
                    // is allocated and owned by WSMan.
                    _requestDetails = null;
                }
            }
            finally
            {
                // dispose resources
                _waitHandle.Dispose();
            }
        }
示例#31
0
文件: test.cs 项目: mono/gert
	static Stream EndGetRequestStreamWithTimeout (HttpWebRequest request, IAsyncResult asyncResult, RegisteredWaitHandle handle)
	{
		try {
			handle.Unregister (asyncResult.AsyncWaitHandle);

			return request.EndGetRequestStream (asyncResult);
		} catch (WebException ex) {
			if (ex.Status == WebExceptionStatus.RequestCanceled) {
				throw new WebException ("GetRequestStream operation has timed out.", WebExceptionStatus.Timeout);
			}

			throw;
		}
	}
示例#32
0
 private void RegisterTimeOut(WaitHandle wait)
 {
     waitHandle           = wait;
     registeredWaitHandle = ThreadPool.RegisterWaitForSingleObject(wait, Callback, null, TIMEOUT_TIME, true);
 }