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; }
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); }
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(); }
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 }
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); } } }
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); }
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); } } }
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); }
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); }
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 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); } }
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; }
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); }
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 }
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; }
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; }
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); } }
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; }
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); } }); }
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); }
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); }
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); }
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); }
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); }
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); }
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; }
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; }
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); }
public void FailedIsTrueIfFutureValueIsException () { var f = new Future<object>(); f.Fail(new Exception("test")); Assert.IsTrue(f.Failed); }
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; }
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); }
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; }
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); }
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); }
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); }