/// <summary> /// Fails the Future, or throws an exception /// if the Future has already been set or failed. /// </summary> public void Fail(Future.FailureType inType, object inArg) { if (m_State == FutureState.Cancelled) { return; } if (m_State != FutureState.InProgress) { throw new InvalidOperationException("Cannot fail Future once Future has completed or failed!"); } m_State = FutureState.Failed; m_Failure.Type = inType; m_Failure.Object = inArg; if (m_CallbackFail != null) { Async.InvokeAsync(m_CallbackFail); m_CallbackFail = null; } if (m_CallbackFailWithArgs != null) { Async.InvokeAsync(InvokeFailure, m_CallbackFailWithArgs); m_CallbackFailWithArgs = null; } m_CallbackComplete = null; m_CallbackProgress = null; }
public Future(Action <T> inCompleteCallback, Action <Future.Failure> inFailureCallback) { m_State = FutureState.InProgress; m_Value = default(T); m_CallbackComplete = inCompleteCallback; m_CallbackFailWithArgs = inFailureCallback; }
/// <summary> /// Sets the future to complete, or throws an exception /// if the Future has already been completed or failed. /// </summary> public void Complete() { if (m_State == FutureState.Cancelled) { return; } if (m_State != FutureState.InProgress) { throw new InvalidOperationException("Cannot set value of Future once Future has completed or failed!"); } m_State = FutureState.Completed; // Force progress to 1. if (m_Progress < 1) { m_Progress = 1; if (m_CallbackProgress != null) { Async.InvokeAsync(m_CallbackProgress, m_Progress); } m_CallbackProgress = null; } if (m_CallbackComplete != null) { Async.InvokeAsync(m_CallbackComplete); m_CallbackComplete = null; } m_CallbackFail = null; m_CallbackFailWithArgs = null; }
public Future(Action <T> inCompleteCallback) { m_State = FutureState.InProgress; m_Value = default(T); m_CallbackComplete = inCompleteCallback; m_CallbackFail = null; }
public Future() { m_State = FutureState.InProgress; m_Value = default(T); m_CallbackComplete = null; m_CallbackFail = null; }
private void FailImpl(Exception error) { _value = default(T); _error = error; _state = FutureState.Error; Dispatcher.InvokeAsync(FlushErrorCallbacks); }
private void AssignImpl(T value) { _value = value; _error = null; _state = FutureState.Success; Dispatcher.InvokeAsync(FlushSuccessCallbacks); }
private void AssignImpl(T value) { _value = value; _error = null; _state = FutureState.Success; FlushSuccessCallbacks(); }
private void FailImpl(Exception error) { _value = default(T); _error = error; _state = FutureState.Error; FlushErrorCallbacks(); }
public void SetError(ushort errorCode, string error) { State = FutureState.Error; Error = error; ErrorCode = errorCode; if (OnError != null) OnError(errorCode, error); }
/// <summary> /// Cancels the Future. It will no longer receive Complete or Fail calls. /// </summary> public void Cancel() { if (m_State == FutureState.InProgress) { m_State = FutureState.Cancelled; m_Prophet.Stop(); m_Async.Cancel(); } }
public void OnResponse(ResponseEnvelope envelope) { if (envelope == null) { throw new ArgumentNullException(nameof(envelope)); } isCompleted = true; Result = envelope; ResultState = envelope != null ? FutureState.Valid : FutureState.Invalid; ApiUrl = envelope.ApiUrl; ticket = envelope.AuthTicket; }
/// <summary> /// Implemetaion of the actual value retrieval. /// </summary> /// <returns> /// The computed value. /// </returns> /// <exception cref="ExecutionException"> if the task completed with an /// error.</exception> /// <exception cref="InvalidOperationException">You try to get the value /// while it is computing (IsCompleted = false).</exception> T GetValue() { FutureState state = (FutureState)state_; switch (state) { case FutureState.Completed: if (exception_ != null) { throw new ExecutionException(exception_); } return(value_); case FutureState.Cancelled: throw new OperationCanceledException("Task was cancelled"); default: throw new InvalidOperationException( "Future is in a invalid state: " + state); } }
/// <summary> /// Called when <see cref="RestSharp"/> recieves a response envelope async. /// </summary> /// <param name="envelope">Response envelope recieved.</param> public virtual void OnResponse(ResponseEnvelope envelope) { Throw <ArgumentNullException> .If.IsNull(envelope)?.Now(nameof(envelope), $"Recieved a null {nameof(ResponseEnvelope)}"); //When this is called we should lock because we're about to dramatically change state lock (syncObj) { //We should check the bytes returned in a response //We expect a Payload. if (envelope.Returns.Count > 0) { Result = envelope; ResultState = FutureState.Valid; isCompleted = true; } else { ResultState = FutureState.Invalid; isCompleted = true; } } }
/// <summary> /// Begins running a given function on a background thread to resolve the future's value, as long /// as it is still in the Pending state. /// </summary> /// <param name="func">The function that will retrieve the desired value.</param> public IFuture <T> Process(Func <T> func) { if (_state != FutureState.Pending) { throw new InvalidOperationException("Cannot process a future that isn't in the Pending state."); } _state = FutureState.Processing; ThreadPool.QueueUserWorkItem(_ => { try { // Directly call the Impl version to avoid the state validation of the public method AssignImpl(func()); } catch (Exception e) { // Directly call the Impl version to avoid the state validation of the public method FailImpl(e); } }); return(this); }
public void SetPathTraceColour(FutureState state) { switch (state) { case FutureState.OK: LineRenderer.startColor = new Color(100, 100, 100); LineRenderer.endColor = new Color(100, 100, 100); break; case FutureState.PlanetHit: LineRenderer.startColor = new Color(200, 0, 0); LineRenderer.endColor = new Color(200, 0, 0); break; case FutureState.CheckpointHit: LineRenderer.startColor = new Color(0, 200, 0); LineRenderer.endColor = new Color(0, 200, 0); break; default: break; } }
/// <summary> /// Implementation of completing a task. /// </summary> /// <param name="value"> /// The value to set as the result of the computation. /// </param> /// <param name="exception"> /// The exception to set as the result of the computation. /// </param> /// <param name="final_state"> /// The state to transiton to. /// </param> /// <param name="synchronously"> /// A indication of whether the operation completed synchronously. /// </param> /// <remarks> /// Either <see cref="value"/> or <see cref="exception"/> will be set but /// not both. The <see cref="final_state"/> is the state to change to from /// RUNNING. If the state is not in the RUNNING state we return /// <c>false</c> after waiting for the state to be set to a valid final /// state(COMPLETED or CANCELLED). /// </remarks> /// <returns> /// <c>false</c> if the state is not in the RUNNING state; otherwise, /// <c>true</c>. /// </returns> /// <remarks> /// A operation is considered synchronously when it runs in the same /// context(Thread) as its initiator. /// </remarks> bool Complete(T value, Exception exception, FutureState final_state, bool synchronously) { int completion = Interlocked.CompareExchange(ref state_, (int)FutureState.Completing, (int)FutureState.Running); if (completion == (int)FutureState.Running) { // If this thread succesfully transitioned to Completing, set the // value and exception and then release to the final state. value_ = value; exception_ = exception; state_ = (int)final_state; completed_synchronously_ = synchronously; sync_.Set(); } else if (state_ == (int)FutureState.Completing) { // If some thread is currently completing the future, block until // they are done so we can guarantee completion. sync_.WaitOne(); } return(completion == (int)FutureState.Running); }
static FutureState ParseFutureState(JToken data, Currency currency) { // { // "amount":"1", // "contract_id":"20160212034", // "contract_name":"BTC0212", // "contract_type":"this_week", // "create_date":"1454855333918", // "create_date_str":"2016-02-07 22:28:53", // "deal_amount":"0", // "fee":"0", // "lever_rate":"10", // "orderid":1502057218, // "price":"375", // "price_avg":"0", // "status":"0", // "type":"1", // "unit_amount":"100" // } var res = new FutureState() { Timestamp = Util.Time.FromUnixMillis((long)data["create_date"]), OrderId = (long)data["orderid"], OrderStatus = Serialization.ParseOrderStatus((int)data["status"]), Product = new Future() { Currency = currency, FutureType = Serialization.ParseFutureType((string)data["contract_type"]), }, Amount = new Amount() { Price = data["price"].AsDecimal(), Quantity = data["amount"].AsDecimal(), }, CumFillQuantity = data["deal_amount"].AsDecimal(), AvgFillPrice = data["price_avg"].AsDecimal(), Fee = data["fee"].AsDecimal(), ContractId = (string)data["contract_id"], }; // Infer CoinType from "contract_name". E.g., "BTC0212" => CoinType.Btc. string contract = (string)data["contract_name"]; Condition.Requires(contract, "contract").IsNotNullOrEmpty(); if (contract.StartsWith("BTC")) { res.Product.CoinType = CoinType.Btc; } else if (contract.StartsWith("LTC")) { res.Product.CoinType = CoinType.Ltc; } else { throw new ArgumentException("Unknown value of `contract_name`: " + contract); } // Decompose "type" into Side and PositionType. int type = (int)data["type"]; switch (type) { case 1: res.Amount.Side = Side.Buy; res.PositionType = PositionType.Long; break; case 2: res.Amount.Side = Side.Buy; res.PositionType = PositionType.Short; break; case 3: res.Amount.Side = Side.Sell; res.PositionType = PositionType.Long; break; case 4: res.Amount.Side = Side.Sell; res.PositionType = PositionType.Short; break; default: throw new ArgumentException("Unknown `type`: " + type); } return(res); }
public void Finish() { _state = FutureState.Success; FlushSuccessCallbacks(); }
public Future() { m_State = FutureState.InProgress; m_CallbackComplete = null; m_CallbackFail = null; }
public Future(Action inCompleteCallback, Action inFailureCallback) { m_State = FutureState.InProgress; m_CallbackComplete = inCompleteCallback; m_CallbackFail = inFailureCallback; }
public void BeginProcess(T initialItem = default(T)) { _state = FutureState.Processing; _value = initialItem; }
/// <summary> /// Initializes a new instance of the <see cref="Future{T}"/> class. /// </summary> public Future() { _state = FutureState.Pending; }
public void SetCompleted() { State = FutureState.Completed; if (OnCompleted != null) OnCompleted(); }