示例#1
0
 public Future<int> Read(byte[] buffer, int offset, int count)
 {
     var f = new Future<int>();
     if (!_Socket.Connected) {
         if (ThrowOnDisconnect)
             f.Fail(new SocketDisconnectedException());
         else
             f.Complete(0);
     } else {
         SocketError errorCode;
         if (_Socket.Available >= count) {
             try {
                 int bytesRead = _Socket.Receive(buffer, offset, count, SocketFlags.None, out errorCode);
                 if (ThrowOnDisconnect && (bytesRead == 0)) {
                     f.Fail(new SocketDisconnectedException());
                 } else {
                     f.Complete(bytesRead);
                 }
             } catch (Exception ex) {
                 f.Fail(ex);
             }
         } else {
             _Socket.BeginReceive(buffer, offset, count, SocketFlags.None, out errorCode, _ReadCallback, f);
         }
     }
     return f;
 }
示例#2
0
文件: IO.cs 项目: sq/Libraries
        private Future <int> DecodeMoreData()
        {
            var f        = new Future <int>();
            var readData = ReadMoreData();

            readData.RegisterOnComplete((_) => {
                if (IsDisposed)
                {
                    f.Dispose();
                    return;
                }

                var error = _.Error;
                if (error != null)
                {
                    f.Fail(error);
                    return;
                }

                var bytesRead = (int)_.Result;

                try {
                    DecodeBuffer(bytesRead);

                    f.Complete(_DecodedCharacterCount);
                } catch (FutureHandlerException) {
                    throw;
                } catch (Exception ex) {
                    f.Fail(ex);
                }
            });
            return(f);
        }
示例#3
0
            public void Execute(Tangle <T> tangle)
            {
                if (!Future.Disposed)
                {
                    try {
                        U result;
                        OnExecute(tangle, out result);

                        if (!Future.Completed)
                        {
                            if (Failure != null)
                            {
                                Future.Fail(Failure);
                            }
                            else
                            {
                                Future.Complete(result);
                            }
                        }
                    } catch (Exception ex) {
                        if (!Future.Disposed && !Future.Completed)
                        {
                            try {
                                Future.Fail(ex);
                            } catch {
                            }
                        }
                    }
                }

                Dispose();
            }
示例#4
0
        public static Future <int> AsyncRead(this Stream stream, byte[] buffer, int offset, int count)
        {
#if XBOX
            return(Future.RunInThread(() => stream.Read(buffer, offset, count)));
#else
            var f = new Future <int>();
            try {
                stream.BeginRead(buffer, offset, count, (ar) => {
                    try {
                        int bytesRead;
                        lock (stream)
                            bytesRead = stream.EndRead(ar);
                        f.Complete(bytesRead);
                    } catch (FutureHandlerException) {
                        throw;
                    } catch (Exception ex) {
                        f.Fail(ex);
                    }
                }, stream);
            } catch (Exception ex) {
                f.Fail(ex);
            }
            return(f);
#endif
        }
示例#5
0
文件: IO.cs 项目: sq/Libraries
            private void _OnDecodeComplete(IFuture f)
            {
                if (Parent.IsDisposed)
                {
                    Result.Dispose();
                    return;
                }

                var e = f.Error;

                if (e != null)
                {
                    Result.Fail(e);
                }
                else
                {
                    int numChars = (int)f.Result;

                    if (numChars > 0)
                    {
                        ProcessDecodedChars();
                    }
                    else
                    {
                        Result.Complete(Position - InitialPosition);
                    }
                }
            }
示例#6
0
文件: IOTests.cs 项目: sq/Libraries
        public void FillingSendBufferCausesWriteToBlock()
        {
            byte[] buf = new byte[102400];

            StreamA.Write(buf, 0, buf.Length);

            var f = new Future <object>();

            ThreadPool.QueueUserWorkItem((_) => {
                try {
                    StreamA.Write(buf, 0, buf.Length);
                    f.Complete();
                } catch (Exception ex) {
                    f.Fail(ex);
                }
            }, null);

            Thread.Sleep(3000);

            Assert.IsFalse(f.Completed, "Expected a full send buffer to make write operation block");

            A.Close();
            B.Close();
            StreamA.Dispose();
            StreamB.Dispose();

            GC.Collect();

            Thread.Sleep(1000);

            Assert.IsTrue(f.Completed);
            Assert.IsTrue(f.Failed);
        }
示例#7
0
文件: IO.cs 项目: sq/Libraries
            void _OnDecodeComplete(IFuture f)
            {
                if (Parent.IsDisposed)
                {
                    Result.Dispose();
                    return;
                }

                var e = f.Error;

                if (e != null)
                {
                    Buffer.Dispose();
                    Result.Fail(e);
                }
                else
                {
                    int numChars = (int)f.Result;

                    if (numChars > 0)
                    {
                        ProcessDecodedChars();
                    }
                    else
                    {
                        string resultString = Buffer.DisposeAndGetContents();
                        if (resultString.Length == 0)
                        {
                            resultString = null;
                        }

                        Result.Complete(resultString);
                    }
                }
            }
示例#8
0
        public Future <int> Read(byte[] buffer, int offset, int count)
        {
            if (IsDisposed)
            {
                throw new ObjectDisposedException("SocketDataAdapter");
            }

            var f = new Future <int>();

            if (!_Socket.Connected)
            {
                if (ThrowOnDisconnect)
                {
                    f.Fail(new SocketDisconnectedException());
                }
                else
                {
                    f.Complete(0);
                }
            }
            else
            {
                SocketError errorCode;
                if (_Socket.Available >= count)
                {
                    try {
                        int bytesRead = _Socket.Receive(buffer, offset, count, SocketFlags.None, out errorCode);
                        if (ThrowOnDisconnect && (bytesRead == 0))
                        {
                            f.Fail(new SocketDisconnectedException());
                        }
                        else
                        {
                            f.Complete(bytesRead);
                        }
                    } catch (Exception ex) {
                        f.Fail(ex);
                    }
                }
                else
                {
                    _Socket.BeginReceive(buffer, offset, count, SocketFlags.None, out errorCode, _ReadCallback, f);
                }
            }
            return(f);
        }
示例#9
0
        public IFuture <StreamItemContainer <TResult> > Stream <TResult>(string target, params object[] args)
        {
            var future = new Future <StreamItemContainer <TResult> >();

            long id = InvokeImp(target,
                                args,
                                callback: (message) =>
            {
                switch (message.type)
                {
                // StreamItem message contains only one item.
                case Messages.MessageTypes.StreamItem:
                    {
                        var container = future.value;

                        if (container.IsCanceled)
                        {
                            break;
                        }

                        container.AddItem((TResult)this.Protocol.ConvertTo(typeof(TResult), message.item));

                        // (re)assign the container to raise OnItem event
                        future.AssignItem(container);
                        break;
                    }

                case Messages.MessageTypes.Completion:
                    {
                        bool isSuccess = string.IsNullOrEmpty(message.error);
                        if (isSuccess)
                        {
                            var container = future.value;

                            // While completion message must not contain any result, this should be future-proof
                            //if (!container.IsCanceled && message.Result != null)
                            //{
                            //    TResult[] results = (TResult[])this.Protocol.ConvertTo(typeof(TResult[]), message.Result);
                            //
                            //    container.AddItems(results);
                            //}

                            future.Assign(container);
                        }
                        else
                        {
                            future.Fail(new Exception(message.error));
                        }
                        break;
                    }
                }
            },
                                isStreamingInvocation: true);

            future.BeginProcess(new StreamItemContainer <TResult>(id));

            return(future);
        }
示例#10
0
文件: IO.cs 项目: sq/Libraries
        public Future <char> Read(bool advance = true)
        {
            var f = new Future <char>();

            SetPendingOperation(f);

            char result;

            if (!GetCurrentCharacter(out result))
            {
                var decodeMoreChars = DecodeMoreData();
                decodeMoreChars.RegisterOnComplete((_) => {
                    if (IsDisposed)
                    {
                        f.Dispose();
                        return;
                    }

                    var error = _.Error;
                    if (error != null)
                    {
                        ClearPendingOperation(f);
                        f.Fail(error);
                    }
                    else
                    {
                        char ch;
                        if (GetCurrentCharacter(out ch))
                        {
                            if (advance)
                            {
                                ReadNextCharacter();
                            }
                            ClearPendingOperation(f);
                            f.Complete(ch);
                        }
                        else
                        {
                            ClearPendingOperation(f);
                            f.Complete(null);
                        }
                    }
                });
            }
            else
            {
                if (advance)
                {
                    ReadNextCharacter();
                }
                ClearPendingOperation(f);
                f.Complete(result);
            }

            return(f);
        }
示例#11
0
 public void GettingResultThrowsExceptionIfFutureValueIsException () {
     var f = new Future<object>();
     f.Fail(new Exception("test"));
     try {
         var _ = f.Result;
         Assert.Fail();
     } catch (FutureException e) {
         Assert.AreEqual("test", e.InnerException.Message);
     }
 }
示例#12
0
 public static Future<Packet> AsyncSend(
     this Session session, Packet packet
 )
 {
     var f = new Future<Packet>();
     session.BeginSend(packet, (_) => {
         try {
             f.Complete(session.EndSend(_));
         } catch (Exception ex) {
             f.Fail(ex);
         }
     });
     return f;
 }
示例#13
0
 public static Future<TcpClient> AcceptIncomingConnection (this TcpListener listener) {
     var f = new Future<TcpClient>();
     listener.BeginAcceptTcpClient((ar) => {
         try {
             TcpClient result = listener.EndAcceptTcpClient(ar);
             f.Complete(result);
         } catch (FutureHandlerException) {
             throw;
         } catch (Exception ex) {
             f.Fail(ex);
         }
     }, null);
     return f;
 }
        public static Future <Packet> AsyncSend(
            this Session session, Packet packet
            )
        {
            var f = new Future <Packet>();

            session.BeginSend(packet, (_) => {
                try {
                    f.Complete(session.EndSend(_));
                } catch (Exception ex) {
                    f.Fail(ex);
                }
            });
            return(f);
        }
示例#15
0
文件: IO.cs 项目: mbahar94/fracture
        public static Future<int> AsyncRead (this Stream stream, byte[] buffer, int offset, int count) {
#if XBOX
            return Future.RunInThread(() => stream.Read(buffer, offset, count));
#else
            var f = new Future<int>();
            try {
                stream.BeginRead(buffer, offset, count, (ar) => {
                    try {
                        int bytesRead;
                        lock (stream)
                            bytesRead = stream.EndRead(ar);
                        f.Complete(bytesRead);
                    } catch (FutureHandlerException) {
                        throw;
                    } catch (Exception ex) {
                        f.Fail(ex);
                    }
                }, stream);
            } catch (Exception ex) {
                f.Fail(ex);
            }
            return f;
#endif
        }
示例#16
0
 public static Future<TcpClient> ConnectTo (string host, int port) {
     var f = new Future<TcpClient>();
     TcpClient client = new TcpClient();
     client.BeginConnect(host, port, (ar) => {
         try {
             client.EndConnect(ar);
             f.Complete(client);
         } catch (FutureHandlerException) {
             throw;
         } catch (Exception ex) {
             f.Fail(ex);
             client.Close();
         }
     }, null);
     return f;
 }
示例#17
0
文件: Misc.cs 项目: mbahar94/fracture
 public static IFuture AsyncExecuteScalar (this IDbCommand cmd) {
     var f = new Future<object>();
     ThreadPool.QueueUserWorkItem(
         (WaitCallback)(
             (state) => {
                 try {
                     object result;
                     result = cmd.ExecuteScalar();
                     f.SetResult(result, null);
                 } catch (Exception e) {
                     f.Fail(e);
                 }
             }
         )
     );
     return f;
 }
示例#18
0
        private IEnumerator ParseColorRoutine(Future <Color> inFuture, string inString)
        {
            // Simulate doing some work with a delay
            yield return(1);

            Color color;
            bool  bSuccess = ColorUtility.TryParseHtmlString(inString, out color);

            if (!bSuccess)
            {
                inFuture.Fail();
            }
            else
            {
                inFuture.Complete(color);
            }
        }
示例#19
0
文件: Misc.cs 项目: mbahar94/fracture
 public static Future<IDataReader> AsyncExecuteReader (this IDbCommand cmd) {
     var f = new Future<IDataReader>();
     ThreadPool.QueueUserWorkItem(
         (WaitCallback)(
             (state) => {
                 try {
                     IDataReader result;
                     result = cmd.ExecuteReader();
                     f.SetResult(result, null);
                 } catch (Exception e) {
                     f.Fail(e);
                 }
             }
         )
     );
     return f;
 }
示例#20
0
文件: Query.cs 项目: sq/NDexer
        private Action GetExecuteFunc <T> (object[] parameters, Func <IFuture, T> queryFunc, Future <T> future)
        {
            if (_Manager == null)
            {
                throw new ObjectDisposedException("query");
            }

            return(() => {
                try {
                    BindParameters(parameters);
                    T result = queryFunc(future);
                    future.SetResult(result, null);
                } catch (Exception e) {
                    future.Fail(e);
                }
            });
        }
示例#21
0
 public static Future<Session> AsyncLogin(
     string username, string password, string resource, 
     bool enableNonSASLAuth, ConnectionOptions options
 )
 {
     var f = new Future<Session>();
     Session.BeginLogin(
         username, password, resource, enableNonSASLAuth, options,
         (_) => {
             try {
                 f.Complete(Session.EndLogin(_));
             } catch (Exception ex) {
                 f.Fail(ex);
             }
         }, null
     );
     return f;
 }
        public static Future <Session> AsyncLogin(
            string username, string password, string resource,
            bool enableNonSASLAuth, ConnectionOptions options
            )
        {
            var f = new Future <Session>();

            Session.BeginLogin(
                username, password, resource, enableNonSASLAuth, options,
                (_) => {
                try {
                    f.Complete(Session.EndLogin(_));
                } catch (Exception ex) {
                    f.Fail(ex);
                }
            }, null
                );
            return(f);
        }
示例#23
0
文件: Misc.cs 项目: sq/NDexer
            public static IFuture AsyncExecuteScalar(this IDbCommand cmd)
            {
                var f = new Future <object>();

                ThreadPool.QueueUserWorkItem(
                    (WaitCallback)(
                        (state) => {
                    try {
                        object result;
                        result = cmd.ExecuteScalar();
                        f.SetResult(result, null);
                    } catch (Exception e) {
                        f.Fail(e);
                    }
                }
                        )
                    );
                return(f);
            }
示例#24
0
文件: Misc.cs 项目: sq/NDexer
            public static Future <IDataReader> AsyncExecuteReader(this IDbCommand cmd)
            {
                var f = new Future <IDataReader>();

                ThreadPool.QueueUserWorkItem(
                    (WaitCallback)(
                        (state) => {
                    try {
                        IDataReader result;
                        result = cmd.ExecuteReader();
                        f.SetResult(result, null);
                    } catch (Exception e) {
                        f.Fail(e);
                    }
                }
                        )
                    );
                return(f);
            }
示例#25
0
        internal UploadItemController <TResult> Upload <TResult>(string target, int paramCount)
        {
            Future <TResult> future = new Future <TResult>();

            Action <Message> callback = (Message message) => {
                bool isSuccess = string.IsNullOrEmpty(message.error);
                if (isSuccess)
                {
                    future.Assign((TResult)this.Protocol.ConvertTo(typeof(TResult), message.result));
                }
                else
                {
                    future.Fail(new Exception(message.error));
                }
            };

            long invocationId = System.Threading.Interlocked.Increment(ref this.lastInvocationId);

            int[] streamIds = new int[paramCount];
            for (int i = 0; i < paramCount; i++)
            {
                streamIds[i] = System.Threading.Interlocked.Increment(ref this.lastStreamId);
            }

            var controller = new UploadItemController <TResult>(this, invocationId, streamIds, future);

            var messageToSend = new Message
            {
                type         = MessageTypes.Invocation,
                invocationId = invocationId.ToString(),
                target       = target,
                arguments    = new object[0],
                streamIds    = streamIds,
                nonblocking  = false,
            };

            SendMessage(messageToSend);

            this.invocations.Add(invocationId, callback);

            return(controller);
        }
示例#26
0
        public IFuture <bool> Send(string target, params object[] args)
        {
            Future <bool> future = new Future <bool>();

            InvokeImp(target,
                      args,
                      (message) =>
            {
                bool isSuccess = string.IsNullOrEmpty(message.error);
                if (isSuccess)
                {
                    future.Assign(true);
                }
                else
                {
                    future.Fail(new Exception(message.error));
                }
            });

            return(future);
        }
示例#27
0
        public IFuture <TResult> Invoke <TResult>(string target, params object[] args)
        {
            Future <TResult> future = new Future <TResult>();

            InvokeImp(target,
                      args,
                      (message) =>
            {
                bool isSuccess = string.IsNullOrEmpty(message.error);
                if (isSuccess)
                {
                    future.Assign((TResult)this.Protocol.ConvertTo(typeof(TResult), message.result));
                }
                else
                {
                    future.Fail(new Exception(message.error));
                }
            });

            return(future);
        }
示例#28
0
文件: Network.cs 项目: sq/Fracture
 public static Future<int> AsyncSend(this UdpClient udpClient, byte[] datagram, int bytes, string hostname, int port)
 {
     var f = new Future<int>();
     try {
         udpClient.BeginSend(
             datagram, bytes, hostname, port,
             (ar) => {
                 try {
                     var bytesSent = udpClient.EndSend(ar);
                     f.Complete(bytesSent);
                 } catch (FutureHandlerException) {
                     throw;
                 } catch (Exception ex) {
                     f.Fail(ex);
                 }
             },
             null
         );
     } catch (Exception ex) {
         f.Fail(ex);
     }
     return f;
 }
示例#29
0
文件: IO.cs 项目: sq/Fracture
        private Future<int> DecodeMoreData()
        {
            var f = new Future<int>();
            var readData = ReadMoreData();
            readData.RegisterOnComplete((_) => {
                if (IsDisposed) {
                    f.Dispose();
                    return;
                }

                var error = _.Error;
                if (error != null) {
                    f.Fail(error);
                    return;
                }

                var bytesRead = (int)_.Result;

                try {
                    DecodeBuffer(bytesRead);

                    f.Complete(_DecodedCharacterCount);
                } catch (FutureHandlerException) {
                    throw;
                } catch (Exception ex) {
                    f.Fail(ex);
                }
            });
            return f;
        }
示例#30
0
文件: IO.cs 项目: sq/Fracture
        public Future<char> Read(bool advance = true)
        {
            var f = new Future<char>();

            SetPendingOperation(f);

            char result;
            if (!GetCurrentCharacter(out result)) {
                var decodeMoreChars = DecodeMoreData();
                decodeMoreChars.RegisterOnComplete((_) => {
                    if (IsDisposed) {
                        f.Dispose();
                        return;
                    }

                    var error = _.Error;
                    if (error != null) {
                        ClearPendingOperation(f);
                        f.Fail(error);
                    } else {
                        char ch;
                        if (GetCurrentCharacter(out ch)) {
                            if (advance)
                                ReadNextCharacter();
                            ClearPendingOperation(f);
                            f.Complete(ch);
                        } else {
                            ClearPendingOperation(f);
                            f.Complete(null);
                        }
                    }
                });
            } else {
                if (advance)
                    ReadNextCharacter();
                ClearPendingOperation(f);
                f.Complete(result);
            }

            return f;
        }
        public DownStreamItemController <TDown> GetDownStreamController <TDown>(string target, params object[] args)
        {
            long invocationId = System.Threading.Interlocked.Increment(ref this.lastInvocationId);

            var future = new Future <TDown>();

            future.BeginProcess();

            var controller = new DownStreamItemController <TDown>(this, invocationId, future);

            Action <Message> callback = (Message msg) =>
            {
                switch (msg.type)
                {
                // StreamItem message contains only one item.
                case MessageTypes.StreamItem:
                {
                    if (controller.IsCanceled)
                    {
                        break;
                    }

                    TDown item = (TDown)this.Protocol.ConvertTo(typeof(TDown), msg.item);

                    future.AssignItem(item);
                    break;
                }

                case MessageTypes.Completion:
                {
                    bool isSuccess = string.IsNullOrEmpty(msg.error);
                    if (isSuccess)
                    {
                        // While completion message must not contain any result, this should be future-proof
                        if (!controller.IsCanceled && msg.result != null)
                        {
                            TDown result = (TDown)this.Protocol.ConvertTo(typeof(TDown), msg.result);

                            future.AssignItem(result);
                        }

                        future.Finish();
                    }
                    else
                    {
                        future.Fail(new Exception(msg.error));
                    }
                    break;
                }
                }
            };

            var message = new Message
            {
                type         = MessageTypes.StreamInvocation,
                invocationId = invocationId.ToString(),
                target       = target,
                arguments    = args,
                nonblocking  = false,
            };

            SendMessage(message);

            if (callback != null)
            {
                this.invocations.Add(invocationId, new InvocationDefinition {
                    callback = callback, returnType = typeof(TDown)
                });
            }

            return(controller);
        }
示例#32
0
 public void FailedIsTrueIfFutureValueIsException () {
     var f = new Future<object>();
     f.Fail(new Exception("test"));
     Assert.IsTrue(f.Failed);
 }
示例#33
0
文件: IO.cs 项目: pakoito/Fracture
        private Future<int> DecodeMoreData()
        {
            var f = new Future<int>();
            var readData = ReadMoreData();
            readData.RegisterOnComplete((_) => {
                if (IsDisposed) {
                    f.Dispose();
                    return;
                }

                var error = _.Error;
                if (error != null) {
                    f.Fail(error);
                    return;
                }

                int bytesRead = (int)(_.Result);

                try {
                    _DecodedCharacterOffset = 0;
                    _DecodedCharacterCount = 0;
                    _DecodedCharacterCount = _Decoder.GetChars(_InputBuffer, 0, bytesRead, _DecodedBuffer, 0);
                    f.Complete(_DecodedCharacterCount);
                } catch (FutureHandlerException) {
                    throw;
                } catch (Exception ex) {
                    f.Fail(ex);
                }
            });
            return f;
        }
示例#34
0
        internal UploadItemController <StreamItemContainer <TResult> > UploadStreamWithDownStream <TResult>(string target, int paramCount)
        {
            Future <StreamItemContainer <TResult> > future = new Future <StreamItemContainer <TResult> >();

            Action <Message> callback = (Message message) => {
                switch (message.type)
                {
                // StreamItem message contains only one item.
                case MessageTypes.StreamItem:
                {
                    StreamItemContainer <TResult> container = future.value;

                    if (container.IsCanceled)
                    {
                        break;
                    }

                    container.AddItem((TResult)this.Protocol.ConvertTo(typeof(TResult), message.item));

                    // (re)assign the container to raise OnItem event
                    future.AssignItem(container);
                    break;
                }

                case MessageTypes.Completion:
                {
                    bool isSuccess = string.IsNullOrEmpty(message.error);
                    if (isSuccess)
                    {
                        StreamItemContainer <TResult> container = future.value;

                        // While completion message must not contain any result, this should be future-proof
                        if (!container.IsCanceled && message.result != null)
                        {
                            TResult result = (TResult)this.Protocol.ConvertTo(typeof(TResult), message.result);

                            container.AddItem(result);
                        }

                        future.Assign(container);
                    }
                    else
                    {
                        future.Fail(new Exception(message.error));
                    }
                    break;
                }
                }
            };

            long invocationId = System.Threading.Interlocked.Increment(ref this.lastInvocationId);

            int[] streamIds = new int[paramCount];
            for (int i = 0; i < paramCount; i++)
            {
                streamIds[i] = System.Threading.Interlocked.Increment(ref this.lastStreamId);
            }

            var controller = new UploadItemController <StreamItemContainer <TResult> >(this, invocationId, streamIds, future);

            var messageToSend = new Message
            {
                type         = MessageTypes.StreamInvocation,
                invocationId = invocationId.ToString(),
                target       = target,
                arguments    = new object[0],
                streamIds    = streamIds,
                nonblocking  = false,
            };

            SendMessage(messageToSend);

            this.invocations.Add(invocationId, callback);

            future.BeginProcess(new StreamItemContainer <TResult>(invocationId));
            return(controller);
        }
示例#35
0
文件: Network.cs 项目: sq/Fracture
 public static Future<Network.UdpPacket> AsyncReceive(this UdpClient udpClient)
 {
     var f = new Future<Network.UdpPacket>();
     try {
         udpClient.BeginReceive((ar) => {
             IPEndPoint endpoint = default(IPEndPoint);
             try {
                 var bytes = udpClient.EndReceive(ar, ref endpoint);
                 f.Complete(new Network.UdpPacket(bytes, endpoint));
             } catch (FutureHandlerException) {
                 throw;
             } catch (Exception ex) {
                 f.Fail(ex);
             }
         }, null);
     } catch (Exception ex) {
         f.Fail(ex);
     }
     return f;
 }
示例#36
0
 public void InvokesOnCompletesWhenFailed () {
     var f = new Future<object>();
     object completeResult = null;
     f.RegisterOnComplete((_) => { completeResult = _.Error ?? _.Result; });
     f.Fail(new Exception("test"));
     Assert.AreEqual("test", (completeResult as Exception).Message);
 }
示例#37
0
文件: Web.cs 项目: pakoito/Fracture
 public static Future<HttpListenerContext> GetContextAsync(this HttpListener listener)
 {
     var f = new Future<HttpListenerContext>();
     listener.BeginGetContext((ar) => {
         try {
             var result = listener.EndGetContext(ar);
             f.Complete(result);
         } catch (FutureHandlerException) {
             throw;
         } catch (Exception ex) {
             f.Fail(ex);
         }
     }, null);
     return f;
 }
        public UpStreamItemController <TResult> GetUpStreamController <TResult>(string target, int paramCount, bool downStream = false)
        {
            Future <TResult> future = new Future <TResult>();

            future.BeginProcess();

            long invocationId = System.Threading.Interlocked.Increment(ref this.lastInvocationId);

            string[] streamIds = new string[paramCount];
            for (int i = 0; i < paramCount; i++)
            {
                streamIds[i] = System.Threading.Interlocked.Increment(ref this.lastStreamId).ToString();
            }

            var controller = new UpStreamItemController <TResult>(this, invocationId, streamIds, future);

            Action <Message> callback = (Message msg) => {
                switch (msg.type)
                {
                // StreamItem message contains only one item.
                case MessageTypes.StreamItem:
                {
                    if (controller.IsCanceled)
                    {
                        break;
                    }

                    TResult item = (TResult)this.Protocol.ConvertTo(typeof(TResult), msg.item);

                    future.AssignItem(item);
                    break;
                }

                case MessageTypes.Completion:
                {
                    bool isSuccess = string.IsNullOrEmpty(msg.error);
                    if (isSuccess)
                    {
                        // While completion message must not contain any result, this should be future-proof
                        if (!controller.IsCanceled && msg.result != null)
                        {
                            TResult result = (TResult)this.Protocol.ConvertTo(typeof(TResult), msg.result);

                            future.AssignItem(result);
                        }

                        future.Finish();
                    }
                    else
                    {
                        var ex = new Exception(msg.error);
                        future.Fail(ex);
                    }
                    break;
                }
                }
            };

            var messageToSend = new Message
            {
                type         = downStream ? MessageTypes.StreamInvocation : MessageTypes.Invocation,
                invocationId = invocationId.ToString(),
                target       = target,
                arguments    = new object[0],
                streamIds    = streamIds,
                nonblocking  = false,
            };

            SendMessage(messageToSend);

            this.invocations.Add(invocationId, new InvocationDefinition {
                callback = callback, returnType = typeof(TResult)
            });

            return(controller);
        }
示例#39
0
文件: IOTests.cs 项目: sq/Fracture
        public void FillingSendBufferCausesWriteToBlock()
        {
            byte[] buf = new byte[102400];

            StreamA.Write(buf, 0, buf.Length);

            var f = new Future<object>();

            ThreadPool.QueueUserWorkItem((_) => {
                try {
                    StreamA.Write(buf, 0, buf.Length);
                    f.Complete();
                } catch (Exception ex) {
                    f.Fail(ex);
                }
            }, null);

            Thread.Sleep(3000);

            Assert.IsFalse(f.Completed, "Expected a full send buffer to make write operation block");

            A.Close();
            B.Close();
            StreamA.Dispose();
            StreamB.Dispose();

            GC.Collect();

            Thread.Sleep(1000);

            Assert.IsTrue(f.Completed);
            Assert.IsTrue(f.Failed);
        }