コード例 #1
0
        public IAsyncResult BeginGetContext(AsyncCallback callback, Object state)
        {
            CheckDisposed();
            if (!listening)
            {
                throw new InvalidOperationException("Please, call Start before using this method.");
            }

            ListenerAsyncResult ares = new ListenerAsyncResult(callback, state);

            // lock wait_queue early to avoid race conditions
            lock (wait_queue)
            {
                lock (ctx_queue)
                {
                    HttpListenerContext ctx = GetContextFromQueue();
                    if (ctx != null)
                    {
                        ares.Complete(ctx, true);
                        return(ares);
                    }
                }

                wait_queue.Add(ares);
            }

            return(ares);
        }
コード例 #2
0
        // Allows creating a pre-completed result with less interlockeds.  Beware!  Constructor calls the callback.
        // if a derived class ever uses this and overloads Cleanup, this may need to change
        internal LazyAsyncResult(object myObject, object myState, AsyncCallback myCallBack, object result)
        {
#if !NETCF
            GlobalLog.Assert(result != DBNull.Value, "LazyAsyncResult#{0}::.ctor()|Result can't be set to DBNull - it's a special internal value.",
                             ValidationHelper.HashString(this));
#endif
            m_AsyncObject   = myObject;
            m_AsyncState    = myState;
            m_AsyncCallback = myCallBack;
            m_Result        = result;
            m_IntCompleted  = 1;

            if (m_AsyncCallback != null)
            {
#if !NETCF
                GlobalLog.Print("LazyAsyncResult#" + ValidationHelper.HashString(this) + "::Complete() invoking callback");
#endif
                m_AsyncCallback(this);
            }
            else
            {
#if !NETCF
                GlobalLog.Print("LazyAsyncResult#" + ValidationHelper.HashString(this) + "::Complete() no callback to invoke");
#endif
            }

#if !NETCF
            GlobalLog.Print("LazyAsyncResult#" + ValidationHelper.HashString(this) + "::.ctor() (pre-completed)");
#endif
        }
コード例 #3
0
 public AsyncReceiveState(SocketClientReceiveAsyncResult asyncResult, AsyncCallback asyncCallback, byte[] buffer, int offset, int reqLength)
 {
     AsyncResult   = asyncResult;
     AsyncCallback = asyncCallback;
     Buffer        = buffer;
     Offset        = offset;
     ReqLength     = reqLength;
 }
コード例 #4
0
 public ForState(IPAddress[] addresses, int port, AsyncCallback callback, object state)
 {
     Addresses = addresses;
     Port      = port;
     Callback  = callback;
     State     = state;
     Index     = 0;
 }
コード例 #5
0
        /// <summary>
        /// Begins to asynchronously send an <see cref="ISnmpMessage"/> to an <see cref="IPEndPoint"/>.
        /// </summary>
        /// <param name="request">The <see cref="ISnmpMessage"/>.</param>
        /// <param name="receiver">Agent.</param>
        /// <param name="registry">The user registry.</param>
        /// <param name="udpSocket">The UDP <see cref="Socket"/> to use to send/receive.</param>
        /// <param name="callback">The callback.</param>
        /// <param name="state">The state object.</param>
        /// <returns></returns>
        public static IAsyncResult BeginGetResponse(
            this ISnmpMessage request, IPEndPoint receiver, UserRegistry registry, Socket udpSocket, AsyncCallback callback, object state)
        {
            if (request == null)
            {
                throw new ArgumentNullException("request");
            }

            if (udpSocket == null)
            {
                throw new ArgumentNullException("udpSocket");
            }

            if (receiver == null)
            {
                throw new ArgumentNullException("receiver");
            }

            if (registry == null)
            {
                throw new ArgumentNullException("registry");
            }

            var requestCode = request.TypeCode();

            if (requestCode == SnmpType.TrapV1Pdu || requestCode == SnmpType.TrapV2Pdu || requestCode == SnmpType.ReportPdu)
            {
                throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, "not a request message: {0}", requestCode));
            }

            // Whatever you change, try to keep the Send and the Receive close to each other.
            udpSocket.SendTo(request.ToBytes(), receiver);
#if CF
            var bufferSize = 8192;
#elif SSHARP
            var bufferSize = 16384;
#else
            var bufferSize = udpSocket.ReceiveBufferSize = Messenger.MaxMessageSize;
#endif
            var buffer = new byte[bufferSize];

            // https://sharpsnmplib.codeplex.com/workitem/7234
            if (callback != null)
            {
                AsyncCallback wrapped = callback;
                callback = asyncResult =>
                {
                    var result = new SnmpMessageAsyncResult(asyncResult, udpSocket, registry, receiver, buffer);
                    wrapped(result);
                };
            }

            var ar = udpSocket.BeginReceive(buffer, 0, bufferSize, SocketFlags.None, callback, state);
            return(new SnmpMessageAsyncResult(ar, udpSocket, registry, receiver, buffer));
        }
コード例 #6
0
        public IAsyncResult BeginConnect(IPAddress address, int port, AsyncCallback callback, object state)
        {
            CheckDisposed();

            if (address == null)
            {
                throw new ArgumentNullException("address");
            }

            return(BeginConnect(new IPEndPoint(address, port), callback, state));
        }
コード例 #7
0
        public IAsyncResult BeginConnect(string host, int port, AsyncCallback callback, object state)
        {
            CheckDisposed();

            if (host == null)
            {
                throw new ArgumentNullException("host");
            }

            var addresses = DnsEx.GetHostAddresses(host);

            return(BeginConnect(addresses, port, callback, state));
        }
コード例 #8
0
        private object m_Event;         // lazy allocated event to be returned in the IAsyncResult for the client to wait on


        internal LazyAsyncResult(object myObject, object myState, AsyncCallback myCallBack)
        {
            m_AsyncObject   = myObject;
            m_AsyncState    = myState;
            m_AsyncCallback = myCallBack;
            m_Result        = DBNull.Value;
#if !NETCF
            GlobalLog.Print("LazyAsyncResult#" + ValidationHelper.HashString(this) + "::.ctor()");
#endif

#if TRACK_LAR
            _MyIndex = Interlocked.Increment(ref _PendingIndex);
            _PendingResults.Add(_MyIndex, this);
#endif
        }
コード例 #9
0
        /// <summary>
        /// Begins getting an incoming request asynchronously.
        /// </summary>
        /// <remarks>
        /// This asynchronous operation must be completed by calling the <c>EndGetContext</c> method.
        /// Typically, the method is invoked by the <paramref name="callback"/> delegate.
        /// </remarks>
        /// <returns>
        /// An <see cref="IAsyncResult"/> that represents the status of the asynchronous operation.
        /// </returns>
        /// <param name="callback">
        /// An <see cref="AsyncCallback"/> delegate that references the method to invoke
        /// when the asynchronous operation completes.
        /// </param>
        /// <param name="state">
        /// An <see cref="object"/> that represents a user defined object to pass to
        /// the <paramref name="callback"/> delegate.
        /// </param>
        /// <exception cref="InvalidOperationException">
        ///   <para>
        ///   This listener has no URI prefix on which listens.
        ///   </para>
        ///   <para>
        ///   -or-
        ///   </para>
        ///   <para>
        ///   This listener hasn't been started, or is currently stopped.
        ///   </para>
        /// </exception>
        /// <exception cref="ObjectDisposedException">
        /// This listener has been closed.
        /// </exception>
        public IAsyncResult BeginGetContext(AsyncCallback callback, Object state)
        {
            CheckDisposed();
            if (_prefixes.Count == 0)
            {
                throw new InvalidOperationException("The listener has no URI prefix on which listens.");
            }

            if (!_listening)
            {
                throw new InvalidOperationException("The listener hasn't been started.");
            }

            return(BeginGetContext(new HttpListenerAsyncResult(callback, state)));
        }
コード例 #10
0
        public IAsyncResult BeginConnect(IPAddress[] addresses, int port, AsyncCallback callback, object state)
        {
            CheckDisposed();

            if (addresses == null || addresses.Any(a => a == null))
            {
                throw new ArgumentNullException("addresses");
            }

            if (addresses.Length == 0)
            {
                throw new ArgumentException("must be at least one address in list", "addresses");
            }

            var forState = new ForState(addresses, port, callback, state);

            return(BeginConnect(new IPEndPoint(addresses[0], port), ForCallback, forState));
        }
コード例 #11
0
        public IAsyncResult BeginConnect(IPEndPoint remoteEP, AsyncCallback callback, object state)
        {
            var client = _client;

            Debug.WriteLine("Client BeginConnect ({0})", remoteEP);

            CheckDisposed();

            client.AddressClientConnectedTo = remoteEP.Address.ToString();
            client.PortNumber = remoteEP.Port;

            var scir = new SocketClientConnectAsyncResult {
                AsyncState = state
            };
            var result = client.ConnectToServerAsync(AsyncConnectComplete, new AsyncConnectState(scir, callback));

            if (result != SocketErrorCodes.SOCKET_OK && result != SocketErrorCodes.SOCKET_OPERATION_PENDING)
            {
                throw new SocketException(result.ToError());
            }

            return(scir);
        }
コード例 #12
0
        internal static PortMapAsyncResult Create(MessageBase message, WebRequest request, AsyncCallback storedCallback, object asyncState)
        {
            if (message is GetGenericPortMappingEntry)
            {
                return(new GetAllMappingsAsyncResult(request, storedCallback, asyncState));
            }

            if (message is GetSpecificPortMappingEntryMessage)
            {
                GetSpecificPortMappingEntryMessage mapMessage = (GetSpecificPortMappingEntryMessage)message;
                GetAllMappingsAsyncResult          result     = new GetAllMappingsAsyncResult(request, storedCallback, asyncState);

                result.SpecificMapping = new Mapping(mapMessage.protocol, 0, mapMessage.externalPort, 0);
                return(result);
            }

            return(new PortMapAsyncResult(request, storedCallback, asyncState));
        }
コード例 #13
0
 protected PortMapAsyncResult(WebRequest request, AsyncCallback callback, object asyncState)
     : base(callback, asyncState)
 {
     this.request = request;
 }
コード例 #14
0
 public ListenerAsyncResult(AsyncCallback cb, object state)
 {
     this.cb    = cb;
     this.state = state;
 }
コード例 #15
0
 public abstract IAsyncResult BeginGetExternalIP(AsyncCallback callback, object asyncState);
コード例 #16
0
 public abstract IAsyncResult BeginDeletePortMap(Mapping mapping, AsyncCallback callback, object asyncState);
コード例 #17
0
 public AsyncSendState(SocketClientSendAsyncResult asyncResult, AsyncCallback asyncCallback)
 {
     AsyncResult   = asyncResult;
     AsyncCallback = asyncCallback;
 }
コード例 #18
0
 public AsyncConnectState(SocketClientConnectAsyncResult asyncResult, AsyncCallback asyncCallback)
 {
     AsyncResult   = asyncResult;
     AsyncCallback = asyncCallback;
 }
コード例 #19
0
 internal HttpListenerAsyncResult(AsyncCallback callback, object state)
 {
     _callback = callback;
     _state    = state;
     _sync     = new object();
 }
コード例 #20
0
        public override IAsyncResult BeginSend(byte[] buffer, int offset, int size, SocketFlags socketFlags, AsyncCallback callback, Object state)
        {
            var client = _client;

            Debug.WriteLine("Client ({0}): BeginSend", InternalRemoteEndPoint);

            CheckDisposed();

            if (_shutdown.HasValue && (_shutdown == SocketShutdown.Send || _shutdown == SocketShutdown.Both))
            {
                throw new SocketException(SocketError.Shutdown);
            }

            if (client.ClientStatus != SocketStatus.SOCKET_STATUS_CONNECTED)
            {
                throw new SocketException(SocketError.NotConnected);
            }

            if (buffer == null)
            {
                throw new ArgumentNullException("buffer");
            }

            if (offset < 0 || offset > buffer.Length)
            {
                throw new ArgumentOutOfRangeException("offset");
            }

            if (size < 0 || size > buffer.Length - offset)
            {
                throw new ArgumentOutOfRangeException("size");
            }

            var ssir = new SocketClientSendAsyncResult {
                AsyncState = state
            };

            if (size == 0)
            {
                ssir.CompletedSynchronously = true;
                ((CEvent)ssir.AsyncWaitHandle).Set();
                ssir.IsCompleted = true;
                ssir.errorCode   = SocketErrorCodes.SOCKET_OK;
                if (callback != null)
                {
                    DoAsyncCallback(callback, ssir);
                }
            }
            else
            {
                var result = client.SendDataAsync(buffer, offset, size, AsyncSendComplete, new AsyncSendState(ssir, callback));

                if (result != SocketErrorCodes.SOCKET_OK && result != SocketErrorCodes.SOCKET_OPERATION_PENDING)
                {
                    throw new SocketException(result.ToError());
                }
            }

            return(ssir);
        }
コード例 #21
0
 internal PortMapAsyncResult(Mapping mapping, AsyncCallback callback, object asyncState)
     : base(callback, asyncState)
 {
     this.mapping = mapping;
 }
コード例 #22
0
 public abstract IAsyncResult BeginGetAllMappings(AsyncCallback callback, object asyncState);
コード例 #23
0
        public override IAsyncResult BeginReceive(byte[] buffer, int offset, int size, SocketFlags socketFlags, AsyncCallback callback, Object state)
        {
            var client = _client;

            Debug.WriteLine("Client ({0}): BeginReceive", InternalRemoteEndPoint);

            CheckDisposed();

            if (buffer == null)
            {
                throw new ArgumentNullException("buffer");
            }

            if (offset < 0 || offset > buffer.Length)
            {
                throw new ArgumentOutOfRangeException("offset");
            }

            if (size < 0 || size > buffer.Length - offset)
            {
                throw new ArgumentOutOfRangeException("size");
            }

            if (_shutdown.HasValue && (_shutdown == SocketShutdown.Receive || _shutdown == SocketShutdown.Both))
            {
                throw new SocketException(SocketError.Shutdown);
            }

            var srir = new SocketClientReceiveAsyncResult {
                AsyncState = state
            };

            if (size == 0)
            {
                srir.CompletedSynchronously = true;
                ((CEvent)srir.AsyncWaitHandle).Set();
                srir.IsCompleted = true;
                srir.errorCode   = SocketErrorCodes.SOCKET_OK;
                if (callback != null)
                {
                    DoAsyncCallback(callback, srir);
                }
            }
            else
            {
                if (dataBuffer.Count == 0)
                {
                    if (finishing)
                    {
                        srir.CompletedSynchronously = true;
                        srir.IsCompleted            = true;
                        ((CEvent)srir.AsyncWaitHandle).Set();
                        if (callback != null)
                        {
                            DoAsyncCallback(callback, srir);
                        }
                    }
                    else
                    {
                        var result = client.ReceiveDataAsync(AsyncReceiveComplete,
                                                             new AsyncReceiveState(srir, callback, buffer, offset, size));

                        if (result != SocketErrorCodes.SOCKET_OK && result != SocketErrorCodes.SOCKET_OPERATION_PENDING)
                        {
                            throw new SocketException(result.ToError());
                        }
                    }
                }
                else
                {
                    int retLength = dataBuffer.Count <= size ? dataBuffer.Count : size;

                    Debug.WriteLine(string.Format("Client ({1}): SyncReceiveComplete [{0}]", retLength, InternalRemoteEndPoint));

                    Buffer.BlockCopy(dataBuffer.ToArray(), 0, buffer, offset, retLength);

                    dataBuffer.RemoveRange(0, retLength);

                    srir.dataReceived = retLength;

                    srir.CompletedSynchronously = true;
                    srir.IsCompleted            = true;
                    ((CEvent)srir.AsyncWaitHandle).Set();
                    if (callback != null)
                    {
                        DoAsyncCallback(callback, srir);
                    }
                }
            }

            return(srir);
        }
コード例 #24
0
 public abstract IAsyncResult BeginGetSpecificMapping(Protocol protocol, int externalPort, AsyncCallback callback, object asyncState);
コード例 #25
0
 internal PortMapAsyncResult(Protocol protocol, int port, int lifetime, AsyncCallback callback, object asyncState)
     : base(callback, asyncState)
 {
     this.mapping = new Mapping(protocol, port, port, lifetime);
 }
コード例 #26
0
		public AsyncResult (AsyncCallback callback, object asyncState)
			{
			this.callback = callback;
			this.asyncState = asyncState;
			waitHandle = new ManualResetEvent (false);
			}
コード例 #27
0
 public GetAllMappingsAsyncResult(WebRequest request, AsyncCallback callback, object asyncState)
     : base(request, callback, asyncState)
 {
     mappings = new List <Mapping> ();
 }