Example #1
0
 /// <summary>
 /// Initializes a new DispatcherOperation Object.
 /// TODO: DOCS
 /// </summary>
 /// <param name="dispatcher"></param>
 /// <param name="priority"></param>
 /// <param name="status"></param>
 /// <param name="task"></param>
 internal DispatcherOperation(Dispatcher dispatcher, DispatcherPriority priority, DispatcherOperationStatus status, Task task)
 {
     Dispatcher = dispatcher ?? throw new ArgumentNullException(nameof(dispatcher));
     Priority   = priority;
     Status     = status;
     Task       = task ?? throw new ArgumentNullException(nameof(task));
 }
Example #2
0
		internal DispatcherOperation (Dispatcher dis, DispatcherPriority prio)
		{
			dispatcher = dis;
			priority = prio;
			if (Dispatcher.HasShutdownFinished)
				status = DispatcherOperationStatus.Aborted;
			else
				status = DispatcherOperationStatus.Pending;
		}
Example #3
0
		internal void Invoke ()
		{
			status = DispatcherOperationStatus.Executing;
			result = delegate_method.DynamicInvoke (delegate_args);
				
			status = DispatcherOperationStatus.Completed;

			if (Completed != null)
				Completed (this, EventArgs.Empty);
		}
Example #4
0
        internal void Invoke()
        {
            status = DispatcherOperationStatus.Executing;
            result = delegate_method.DynamicInvoke(delegate_args);

            status = DispatcherOperationStatus.Completed;

            if (Completed != null)
            {
                Completed(this, EventArgs.Empty);
            }
        }
 internal DispatcherOperation(Dispatcher dis, DispatcherPriority prio)
 {
     this.dispatcher = dis;
     this.priority = prio;
     if (this.Dispatcher.HasShutdownFinished)
     {
         this.status = DispatcherOperationStatus.Aborted;
     }
     else
     {
         this.status = DispatcherOperationStatus.Pending;
     }
 }
Example #6
0
 internal DispatcherOperation(Dispatcher dis, DispatcherPriority prio)
 {
     this.dispatcher = dis;
     this.priority   = prio;
     if (this.Dispatcher.HasShutdownFinished)
     {
         this.status = DispatcherOperationStatus.Aborted;
     }
     else
     {
         this.status = DispatcherOperationStatus.Pending;
     }
 }
        private void UpdateTextThread(string message)
        {
            ThreadStart start = delegate()
            {
                DispatcherOperation operation = Dispatcher.BeginInvoke(DispatcherPriority.Normal,
                                                                       new Action <string>(UpdateText), message);
                DispatcherOperationStatus status = operation.Status;
                while (status != DispatcherOperationStatus.Completed)
                {
                    status = operation.Wait(TimeSpan.FromMilliseconds(100));
                }
            };

            new Thread(start).Start();
        }
Example #8
0
        internal void Invoke()
        {
            this.status = DispatcherOperationStatus.Executing;

            if (this.delegateMethod != null)
            {
                this.result = this.delegateMethod.DynamicInvoke(this.delegateArgs);
            }

            this.status = DispatcherOperationStatus.Completed;

            if (this.Completed != null)
            {
                this.Completed(this, EventArgs.Empty);
            }
        }
Example #9
0
 internal DispatcherOperation(
     Dispatcher dispatcher,
     Delegate method,
     DispatcherPriority priority,
     object[] args,
     CancellationToken cancellationToken,
     DispatcherOperationTaskSource taskSource)
 {
     Dispatcher             = dispatcher;
     this.method            = method;
     Priority               = priority;
     this.args              = args;
     this.cancellationToken = cancellationToken;
     this.taskSource        = taskSource;
     Status = DispatcherOperationStatus.Pending;
 }
Example #10
0
        void CoreInvoke(bool beginInvokeBehavior)
        {
            Status = DispatcherOperationStatus.Executing;

            var oldSynchronizationContext = SynchronizationContext.Current;

            try
            {
                SynchronizationContext.SetSynchronizationContext(Dispatcher.DefaultSynchronizationContext);

                try
                {
                    if (method is Action action)
                    {
                        action();
                    }
                    else
                    {
                        Result = method.DynamicInvoke(args);
                    }
                }
                catch (Exception e)
                {
                    exception = e;
                }

                if (beginInvokeBehavior)
                {
                    if (exception is OperationCanceledException)
                    {
                        Status    = DispatcherOperationStatus.Aborted;
                        exception = null;
                        Aborted?.Invoke(this, EventArgs.Empty);
                    }
                    else
                    {
                        Status = DispatcherOperationStatus.Completed;
                        Completed?.Invoke(this, EventArgs.Empty);
                    }
                }
            }
            finally
            {
                SynchronizationContext.SetSynchronizationContext(oldSynchronizationContext);
            }
        }
        public bool Abort()
        {
            int num = this._dispatcher.Abort(this) ? 1 : 0;

            if (num == 0)
            {
                return(num != 0);
            }
            this._status = DispatcherOperationStatus.Aborted;
            // ISSUE: reference to a compiler-generated field
            GHIElectronics.TinyCLR.UI.EventHandler aborted = this.Aborted;
            if (aborted == null)
            {
                return(num != 0);
            }
            aborted((object)this, EventArgs.Empty);
            return(num != 0);
        }
Example #12
0
        /// <summary>
        /// Runs <paramref name="action"/> on <paramref name="dispatcher"/>, eventually after <paramref name="delay"/>.
        /// Parameter <paramref name="priority"/> sets action priority.
        /// </summary>
        /// <param name="dispatcher">Dispatcher to use.</param>
        /// <param name="action">Action to run.</param>
        /// <param name="delay">Delay, before executing <paramref name="action"/>.</param>
        /// <param name="priority">Opeartion priority.</param>
        public static void Run(Dispatcher dispatcher, Action action, int delay = 0, DispatcherPriority priority = DispatcherPriority.Normal)
        {
            ThreadStart start = delegate()
            {
                if (delay >= 0)
                {
                    Thread.Sleep(delay);
                }

                DispatcherOperation       op     = dispatcher.BeginInvoke(priority, action);
                DispatcherOperationStatus status = op.Status;
                while (status != DispatcherOperationStatus.Completed)
                {
                    status = op.Wait(TimeSpan.FromMilliseconds(intervalCheckDelay));
                }
            };

            new Thread(start).Start();
        }
Example #13
0
                public override bool WaitOne()
                {
                    DispatcherOperationStatus status = _operation.Wait();

                    return(status == DispatcherOperationStatus.Completed);
                }
Example #14
0
        public WebClient DownloadVersion(string revision, LogDelegate log, Dispatcher dispatcher)
        {
            string downloadUrl = Path.Combine(String.Format(Model.Model.DownloadBuildUrl, revision), Model.Model.DownloadFileName);
            string localPath   = Path.Combine(Model.Model.InstallationFolder, Model.Model.DownloadFileName);
            string extractPath = Model.Model.InstallationFolder;

            try
            {
                WebClient client = new WebClient();
                client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(delegate(object sender, DownloadProgressChangedEventArgs e)
                {
                    Model.Model.Status = e.ProgressPercentage;
                });
                client.DownloadFileCompleted += new System.ComponentModel.AsyncCompletedEventHandler(delegate(object sender, AsyncCompletedEventArgs e)
                {
                    if (e.Error == null && e.Cancelled == false)
                    {
                        log(LogType.FileDownloaded);
                        ZipFile zip = new ZipFile(localPath);

                        Action <string, ExtractExistingFileAction> extractAll = zip.ExtractAll;
                        Action finished = () =>
                        {
                            Model.Model.LocalVersion = revision;
                            Model.Model.Status       = 0;
                            log(LogType.FileExtracted);

                            zip.Dispose();
                            File.Delete(localPath);
                        };

                        Model.Model.Status   = 0;
                        zip.ExtractProgress += new EventHandler <ExtractProgressEventArgs>((s, p) =>
                        {
                            if (p.EntriesTotal != 0)
                            {
                                Model.Model.Status = (int)((double)p.EntriesExtracted / p.EntriesTotal * 100);
                            }
                        });

                        extractAll.BeginInvoke(extractPath, ExtractExistingFileAction.OverwriteSilently, (ar) =>
                        {
                            Action <string, ExtractExistingFileAction> a = (ar as System.Runtime.Remoting.Messaging.AsyncResult).AsyncDelegate as Action <string, ExtractExistingFileAction>;
                            try
                            {
                                if (a != null)
                                {
                                    a.EndInvoke(ar);
                                }

                                ThreadStart start = delegate()
                                {
                                    DispatcherOperation op = dispatcher.BeginInvoke(
                                        finished,
                                        DispatcherPriority.Normal
                                        );

                                    DispatcherOperationStatus status = op.Status;
                                    while (status != DispatcherOperationStatus.Completed)
                                    {
                                        status = op.Wait(TimeSpan.FromMilliseconds(1000));
                                        if (status == DispatcherOperationStatus.Aborted)
                                        {
                                            throw new UpdaterException("Dispatcher operation aborted!");
                                        }
                                    }
                                };

                                new Thread(start).Start();
                            }
                            catch (Exception ex)
                            {
                                throw new UpdaterException("Updater exception", ex);
                            }
                        }, null);
                    }
                    else if (e.Error != null)
                    {
                        log(LogType.FileDownloadError, e.Error);
                    }
                    else if (e.Cancelled)
                    {
                        log(LogType.FileDownloadCanceled);
                    }
                });
                client.DownloadFileAsync(new Uri(downloadUrl), localPath);
                return(client);
            }
            catch (Exception ex)
            {
                throw new UpdaterException("Updater exception", ex);
            }
        }
Example #15
0
 public bool Abort()
 {
     this.status = DispatcherOperationStatus.Aborted;
     throw new NotImplementedException();
 }
Example #16
0
 internal void Invoke()
 {
     System.Diagnostics.Debug.Assert(myStatus == DispatcherOperationStatus.Executing);
     try
     {
         myResult = myDelegate.Method.Invoke(myDelegate.Target, myArgs);
     }
     finally
     {
         lock (this)
         {
             myStatus = DispatcherOperationStatus.Completed;
             NotifyInvokeComplete();
         }
     }
 }
Example #17
0
        public void Abort()
        {
            if (Status != DispatcherOperationStatus.Pending)
            {
                throw new Granular.Exception("Operation is \"{0}\" and cannot be aborted", Status);
            }

            Status = DispatcherOperationStatus.Aborted;
            Aborted.Raise(this);
        }
        private void ProcessPrice(Price Price)
        {
            try {
                RaisePropertyChanged(() => DensityAverage);
                if (Visibility == Visibility.Hidden)
                {
                    return;
                }
                var digits = fw.GetDigits(pair);
                ShowSpread(Price);

                var account       = fw.GetAccount();
                var usableMargin  = account.UsableMargin;
                var avalibleTotal = usableMargin * Leverage;
                AmountToBuy  = TradesManagerStatic.GetLotstoTrade(account.Balance, Leverage, lotsToBuyRatio, fw.MinimumQuantity);
                AmountToSell = TradesManagerStatic.GetLotstoTrade(account.Balance, Leverage, lotsToSellRatio, fw.MinimumQuantity);
                var summary = fw.GetSummary() ?? new Order2GoAddIn.Summary();
                ShowAccount(account, summary);
                ShowSummary(summary, account);

                #region Trade (Open)
                var canBuy = chartingWindow.GoBuy && !chartingWindow.CloseBuy &&
                             (chartingWindow.CanTrade || summary.BuyLots > 0) &&
                             (Lib.GetChecked(chkCanBuy).Value || summary.BuyLots > 0);
                var canSell = chartingWindow.GoSell && !chartingWindow.CloseSell &&
                              (chartingWindow.CanTrade || summary.SellLots > 0) &&
                              (Lib.GetChecked(chkCanSell).Value || summary.SellLots > 0);
                if ((isAutoPilot || isAutoAdjust || summary.SellPositions + summary.BuyPositions > 0))
                {
                    var buyTradeDelta = tradeDelta * chartingWindow.DencityRatio;// *averageProfitCMA30_Sell / (averageProfitCMA30_Sell + averageProfitCMA30_Buy);
                    var takeProfitBuy = summary == null || summary.BuyPositions == 0 || chartingWindow.TakeProfitBuy < 0 ? chartingWindow.TakeProfitBuy
            : -chartingWindow.TakeProfitNet(chartingWindow.TakeProfitBuy, summary, true);
                    if ((isAutoPilot || summary.BuyPositions > 0) && canBuy /*&& lots > 0 && fw.CanTrade(true, buyTradeDelta)*/)
                    {
                        try {
                            var lots = chartingWindow.LotsToTradeBuy > 1000 ? chartingWindow.LotsToTradeBuy : chartingWindow.LotsToTradeBuy * AmountToBuy;
                            var l    = fw.CanTrade2(true, buyTradeDelta, lots, tradeDistanceUnisex);
                            lots = chartingWindow.LotsToTradeBuy > 1 && l < lots ? 0 : l;
                            if (lots > 0)
                            {
                                fw.FixOrderOpen(true, lots, takeProfitBuy, chartingWindow.StopLossBuy, chartingWindow.TradeInfo.ToString());
                            }
                        } catch (Order2GoAddIn.FXCoreWrapper.OrderExecutionException exc) {
                            Log = exc;
                        }
                    }
                    var sellTradeDelta = tradeDelta * chartingWindow.DencityRatio;// *averageProfitCMA30_Buy / (averageProfitCMA30_Sell + averageProfitCMA30_Buy);
                    var takeProfitSell = summary == null || summary.SellPositions == 0 || chartingWindow.TakeProfitSell < 0 ? chartingWindow.TakeProfitSell
            : -chartingWindow.TakeProfitNet(chartingWindow.TakeProfitSell, summary, false);
                    if ((isAutoPilot || summary.SellPositions > 0) && canSell /* && lots > 0 && fw.CanTrade(false, sellTradeDelta)*/)
                    {
                        try {
                            var lots = chartingWindow.LotsToTradeSell > 1000 ? chartingWindow.LotsToTradeSell : chartingWindow.LotsToTradeSell * AmountToSell;
                            var l    = fw.CanTrade2(false, sellTradeDelta, lots, tradeDistanceUnisex);
                            lots = chartingWindow.LotsToTradeSell > 1 && l < lots ? 0 : l;
                            if (lots > 0)
                            {
                                fw.FixOrderOpen(false, lots, takeProfitSell, chartingWindow.StopLossSell, chartingWindow.TradeInfo.ToString());
                            }
                        } catch (Order2GoAddIn.FXCoreWrapper.OrderExecutionException exc) {
                            Log = exc;
                        }
                    }

                    if (isAutoAdjust)
                    {
                        var stats = new DispatcherOperationStatus[] { DispatcherOperationStatus.Executing, DispatcherOperationStatus.Pending };
                        if (summary != null && summary.BuyPositions > 0 && takeProfitBuy > 0)
                        {
                            fw.FixOrderSetNetLimits(Math.Abs(takeProfitBuy), true);
                            //if( setLimitThreadBuy != null )
                            //  setLimitThreadBuy.Abort();
                            //setLimitThreadBuy = new Thread(delegate() { fw.FixOrder_SetNetLimits(Math.Abs(takeProfitBuy), true); }) { Priority = ThreadPriority.Lowest };
                            //setLimitThreadBuy.Start();
                        }
                        if (summary != null && summary.SellPositions > 0 && takeProfitSell > 0)
                        {
                            fw.FixOrderSetNetLimits(Math.Abs(takeProfitSell), false);
                            //if (setLimitThreadSell != null)
                            //  setLimitThreadSell.Abort();
                            //setLimitThreadSell = new Thread(delegate() { fw.FixOrder_SetNetLimits(Math.Abs(takeProfitSell), false); }) { Priority = ThreadPriority.Lowest };
                            //setLimitThreadSell.Start();
                        }
                    }
                }
                #endregion
            } catch (ThreadAbortException) {
            } catch (Exception exc) {
                Log = exc;
            }
        }
Example #19
0
        /// <summary>
        /// 树点击事件。
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void NavigationTreeView_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs <object> e)
        {
            var treeViewItem = e.NewValue;

            if (treeViewItem == null || !(treeViewItem is TreeViewItem))
            {
                return;
            }

            HideSidebar();

            // 跟踪树形节点选中队列,保持刚选中的项为最后一项
            TreeViewItemSelectionQueue.Remove(treeViewItem);
            TreeViewItemSelectionQueue.Add(treeViewItem);
            // 如果是换肤节点,则显示换肤控件
            if (treeViewItem == SkinTreeViewItem)
            {
                ShowContent(SkinUserControl);
                return;
            }

            var node = (treeViewItem as TreeViewItem).Tag as NavigationNode;

            if (!string.IsNullOrEmpty(node.Value))
            {
                if (OpenedPagesCache.ContainsKey(node.Id))
                {
                    ShowContent(OpenedPagesCache[node.Id]);
                    return;
                }

                LoadingTextBlock.Visibility = System.Windows.Visibility.Visible;
                LayoutDockPanel.Visibility  = System.Windows.Visibility.Hidden;

                ThreadPool.QueueUserWorkItem(state =>
                {
                    Action action = () =>
                    {
                        bool cached = false;
                        // 缓存中是否存在当前打开的页面,如果有,直接显示


                        // 获取该树节点的Tag属性,其值为导航节点

                        // 加载导航节点定义的用户控件的类型,这个类型由插件提供。
                        // 因此,必须使用插件来加载类型。
                        if (!cached)
                        {
                            var contentClass = node.Bundle.LoadClass(node.Value);
                            if (contentClass != null)
                            {
                                try
                                {
                                    // 创建实例,并转换成用户控件。
                                    var component   = System.Activator.CreateInstance(contentClass);
                                    var userControl = component as UserControl;
                                    if (userControl == null)
                                    {
                                        FileLogUtility.Error(string.Format("The type '{0}' in the Bundle '{1}' does not inherit from UIElement.", node.Value, node.Bundle.SymbolicName));
                                        return;
                                    }

                                    if (userControl.DataContext != null && userControl.DataContext is ListViewModelBase)
                                    {
                                        userControl.InputBindings.AddRange((userControl.DataContext as ListViewModelBase).InputKeyBindings);
                                    }

                                    // 添加到缓存
                                    OpenedPagesCache[node.Id] = userControl;

                                    // 将动态创建控件添加到显示区域
                                    ShowContent(userControl);
                                }
                                catch (Exception ex)
                                {
                                    FileLogUtility.Error(string.Format("Failed to create UIElement for the type '{0}' in the Bundle '{1}'.", node.Value, node.Bundle.SymbolicName));
                                    FileLogUtility.Error(ex);
                                }
                            }
                            else
                            {
                                FileLogUtility.Error(string.Format("Failed to load class '{0}' from the Bundle '{1}'.", node.Value, node.Bundle.SymbolicName));
                            }
                        }

                        LoadingTextBlock.Visibility = System.Windows.Visibility.Hidden;
                        LayoutDockPanel.Visibility  = System.Windows.Visibility.Visible;
                    };

                    DispatcherOperation op = Dispatcher.BeginInvoke(
                        DispatcherPriority.Background,
                        action);

                    DispatcherOperationStatus status = op.Status;
                    while (status != DispatcherOperationStatus.Completed)
                    {
                        status = op.Wait(TimeSpan.FromMilliseconds(1000));
                        if (status == DispatcherOperationStatus.Aborted)
                        {
                            // Alert Someone
                        }
                    }
                });
            }
        }
Example #20
0
		public bool Abort ()
		{
			status = DispatcherOperationStatus.Aborted;
			throw new NotImplementedException ();
		}
Example #21
0
                public override bool WaitOne(TimeSpan timeout)
                {
                    DispatcherOperationStatus status = _operation.Wait(timeout);

                    return(status == DispatcherOperationStatus.Completed);
                }
Example #22
0
        public void Invoke()
        {
            if (Status != DispatcherOperationStatus.Pending)
            {
                throw new Granular.Exception("Operation is \"{0}\" and cannot be invoked", Status);
            }

            Status = DispatcherOperationStatus.Executing;
            Result = action();
            Status = DispatcherOperationStatus.Completed;
            Completed.Raise(this);
        }
        internal void Invoke()
        {
            this.status = DispatcherOperationStatus.Executing;

            if (this.delegateMethod != null)
            {
                this.result = this.delegateMethod.DynamicInvoke(this.delegateArgs);
            }

            this.status = DispatcherOperationStatus.Completed;

            if (this.Completed != null)
            {
                this.Completed(this, EventArgs.Empty);
            }
        }