BeginInvoke() public method

public BeginInvoke ( System.Action a ) : System.Windows.Threading.DispatcherOperation
a System.Action
return System.Windows.Threading.DispatcherOperation
示例#1
0
        public static bool Verify(Dispatcher dispatcher, Stream file)
        {
            if (file.Length == 0)
            {
                dispatcher.BeginInvoke(() =>
                    MessageBox.Show(Resources.EmptyFile,
                        Properties.Resources.DownloadTitle,
                        MessageBoxButton.OK));

                return false;
            }

            if (!DatabaseReader.CheckSignature(file))
            {
                dispatcher.BeginInvoke(() =>
                    MessageBox.Show(Resources.NotKdbx,
                        Properties.Resources.DownloadTitle,
                        MessageBoxButton.OK));

                return false;
            }

            file.Position = 0;
            return true;
        }
示例#2
0
        public SplashWindow()
        {
            InitializeComponent();

            //create our background worker and support cancellation
            worker = new BackgroundWorker();

            worker.DoWork += delegate(object s, DoWorkEventArgs doWorkArgs)
            {
//                try
//                {
                System.Threading.Thread.Sleep(5000);

                //And ask the WPF thread to open the next (OpenFile) Window
                System.Windows.Threading.Dispatcher winDispatcher = this.Dispatcher;
                OpenFilePageDelegate winDelegate = new OpenFilePageDelegate(this.close_click);
                //invoke the dispatcher and pass the percentage and max record count
                winDispatcher.BeginInvoke(winDelegate);
//                }
//                catch (Exception ex)
//                {
//                    ;
//                }
            };
            worker.RunWorkerAsync();
        }
        internal void Refresh(Dispatcher dispatcher)
        {
            dispatcher.BeginInvoke((Action)delegate
            {
                //RGB
                unsafe
                {
                    if (rgbSource != null)
                    {
                        ReadLockedWrapperPtr ptr = ResultsDllWrapper.lockFactoryImage(ImageProductType.RGBSourceProduct);
                        rgbSource.Lock();
                        rgbSource.WritePixels(new Int32Rect(0, 0, rgbWidth, rgbHeight), ptr.IntPtr, rgbWidth * rgbHeight * 3, rgbWidth * 3);
                        rgbSource.Unlock();
                        ResultsDllWrapper.releaseReadLockedWrapperPtr(ptr);
                    }
                }

                //Depth
                unsafe
                {
                    if (depthSource != null)
                    {
                        ReadLockedWrapperPtr ptr = ResultsDllWrapper.lockFactoryImage(ImageProductType.DepthSynchronizedProduct);
                        depthSource.Lock();
                        depthSource.WritePixels(new Int32Rect(0, 0, depthWidth, depthHeight), ptr.IntPtr, depthWidth * depthHeight * 2, depthWidth * 2);
                        depthSource.Unlock();
                        ResultsDllWrapper.releaseReadLockedWrapperPtr(ptr);
                    }
                }
            }, null);
        }
 public static void BeginInvoke(Dispatcher dispatcher, Action action)
 {
     if (IsSynchronous)
         action();
     else
         dispatcher.BeginInvoke(action);
 }
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="url">The url to navigate to when loaded.</param>
 public FacebookWPFBrowser(string url)
 {
     dispatcher = Dispatcher.CurrentDispatcher;
     InitializeComponent();
     _url = url;
     dispatcher.BeginInvoke(new Action(() => this.webBrowser.Navigate(new Uri(_url))));
 }
    /// <summary>Asynchronously invokes an Action on the Dispatcher.</summary>
    /// <param name="dispatcher">The Dispatcher.</param>
    /// <param name="action">The action to invoke.</param>
    /// <returns>A Task that represents the execution of the action.</returns>
    public static Task InvokeAsync(this System.Windows.Threading.Dispatcher dispatcher, Action action)
    {
        if (dispatcher == null)
        {
            throw new ArgumentNullException("dispatcher");
        }
        if (action == null)
        {
            throw new ArgumentNullException("action");
        }

        var tcs = new TaskCompletionSource <VoidTaskResult>();

        dispatcher.BeginInvoke(new Action(() =>
        {
            try
            {
                action();
                tcs.TrySetResult(default(VoidTaskResult));
            }
            catch (Exception exc)
            {
                tcs.TrySetException(exc);
            }
        }));
        return(tcs.Task);
    }
    /// <summary>Asynchronously invokes an Action on the Dispatcher.</summary>
    /// <param name="dispatcher">The Dispatcher.</param>
    /// <param name="function">The function to invoke.</param>
    /// <returns>A Task that represents the execution of the function.</returns>
    public static Task <TResult> InvokeAsync <TResult>(this System.Windows.Threading.Dispatcher dispatcher, Func <TResult> function)
    {
        if (dispatcher == null)
        {
            throw new ArgumentNullException("dispatcher");
        }
        if (function == null)
        {
            throw new ArgumentNullException("function");
        }

        var tcs = new TaskCompletionSource <TResult>();

        dispatcher.BeginInvoke(new Action(() =>
        {
            try
            {
                var result = function();
                tcs.TrySetResult(result);
            }
            catch (Exception exc)
            {
                tcs.TrySetException(exc);
            }
        }));
        return(tcs.Task);
    }
示例#8
0
        public VisualCommentsHelper(Dispatcher disp, ItemContainerGenerator gen, Comment placeholder)
        {
            _gen = gen;
            _placeholder = placeholder;

            disp.BeginInvoke(new Action(DeferredFocusSet),
                             System.Windows.Threading.DispatcherPriority.Background, null);
        }
示例#9
0
 public static void ExecuteAsyncUI(Dispatcher dispatcher, Action action, Action callback)
 {
     DispatcherOperation dispatcherOp = dispatcher.BeginInvoke(action, DispatcherPriority.Normal);
     if (null != callback)
     {
         dispatcherOp.Completed += (s, e) => { callback(); };
     }
 }
        private void ProcessSingleFile(string filename)
        {
            _rowsProcessed         = 0;
            _inputFileStreamLength = 0;
            _jaggedLines           = 0;
            // get the salt from the text box, which may or may not be visible..
            _salt = txtSalt.Text;

            System.Windows.Threading.Dispatcher dispatcher = Dispatcher;

            worker = new BackgroundWorker();
            worker.WorkerSupportsCancellation = true;

            bool wasCancelled = false;
            int  columnIndexSelectedAsNHSNumber = cmbNHSNumber.SelectedIndex;

            // anonymous delegate, this could be moved out for readability?
            worker.DoWork += delegate(object s, DoWorkEventArgs args)
            {
                if (MainWork(filename, columnIndexSelectedAsNHSNumber, dispatcher, ref wasCancelled))
                {
                    return;
                }
            };

            worker.RunWorkerCompleted += delegate(object s, RunWorkerCompletedEventArgs args)
            {
                string configWriteLine = "";
                if (!wasCancelled)
                {
                    configWriteLine = "Processing Finished At: " + DateTime.Now;
                    UpdateProgressDelegate update = new UpdateProgressDelegate(UpdateProgressText);
                    dispatcher.BeginInvoke(update, _inputFileStreamLength, _inputFileStreamLength, _rowsProcessed, _validNHSNumCount, _inValidNHSNumCount, _missingNHSNumCount);
                }
                else
                {
                    configWriteLine = "Processing Cancelled At: " + DateTime.Now;
                }

                var writeConfigStream = new FileStream(_outputRunLogFileName, FileMode.Append, FileAccess.Write);
                using (StreamWriter streamConfigWriter = new StreamWriter(writeConfigStream))
                {
                    streamConfigWriter.WriteLine(configWriteLine);
                    streamConfigWriter.WriteLine("Lines Processed: " + _rowsProcessed);
                    streamConfigWriter.WriteLine("Jagged Lines: " + _jaggedLines);
                    if (_performNHSNumberValidation)
                    {
                        streamConfigWriter.WriteLine("Valid NHSNumbers (10 character number found and passed checksum) : " + _validNHSNumCount);
                        streamConfigWriter.WriteLine("Invalid NHSNumbers (data was present but failed the checksum) : " + _inValidNHSNumCount);
                        streamConfigWriter.WriteLine("Missing NHSNumbers (blank string or space) : " + _missingNHSNumCount);
                    }
                }

                SignRunLogFile();
            };

            worker.RunWorkerAsync();
        }
        public CommentNotificationDeferral(Dispatcher disp, DiscCtx ctx, ItemsControl commentItems)
        {
            _disp = disp;
            _ctx = ctx;
            _commentItems = commentItems;

            _disp.BeginInvoke(new Action(InjectCommentNotifications),
                              System.Windows.Threading.DispatcherPriority.Background);
        }     
示例#12
0
        public static void DoEvents(Dispatcher disp = null) {
            DispatcherFrame frame = new DispatcherFrame();
            if(disp == null) {
                disp = Dispatcher.CurrentDispatcher;
            }

            disp.BeginInvoke(DispatcherPriority.Background, new DispatcherOperationCallback(ExitFrame), frame);
            Dispatcher.PushFrame(frame);
        }
 /// <summary>
 /// Rethrows exceptions thrown during task execution in thespecified dispatcher thread.
 /// </summary>
 /// <param name="task">The task.</param>
 /// <param name="dispatcher">The dispatcher.</param>
 /// <returns></returns>
 public static Task WithExceptionThrowingInDispatcher(this Task task, Dispatcher dispatcher)
 {
     return task.ContinueWith(t =>
     {
         dispatcher.BeginInvoke(() =>
         {
             throw t.Exception;
         }, DispatcherPriority.Send);
     }, TaskContinuationOptions.OnlyOnFaulted);
 }
示例#14
0
        /// <summary>
        /// Raises the <see cref="TaskComplete"/> event.</summary>
        /// <param name="sender">
        /// The <see cref="Object"/> sending the event.</param>
        /// <remarks><para>
        /// <b>OnTaskComplete</b> raises the <see cref="TaskComplete"/> event. Use this method to
        /// notify any listeners that work on the current task is complete.
        /// </para><para>
        /// If <see cref="Dispatcher"/> is valid and <see cref="SysDispatcher.CheckAccess"/> fails,
        /// <b>OnTaskComplete</b> performs an asynchronous delegate invocation via <see
        /// cref="SysDispatcher.BeginInvoke"/> and with the current <see cref="Priority"/>.
        /// </para></remarks>

        public void OnTaskComplete(object sender)
        {
            var handler = TaskComplete;

            if (handler != null)
            {
                if (Dispatcher != null && !Dispatcher.CheckAccess())
                {
                    foreach (EventHandler eh in handler.GetInvocationList())
                    {
                        Dispatcher.BeginInvoke(Priority, eh, sender, EventArgs.Empty);
                    }
                }
                else
                {
                    handler(sender, EventArgs.Empty);
                }
            }
        }
示例#15
0
        public GitHubModel(Dispatcher dispatcher)
        {
            Dispatcher = dispatcher;
            _exceptionAction = ex => Dispatcher.BeginInvoke(() =>
                    MessageBox.Show("Error: " + Enum.GetName(typeof(ErrorType), ex.ErrorType), "", MessageBoxButton.OK)
                );

            _client = new GitHubClient();

            Contexts = new ObservableCollection<Context>();
        }
示例#16
0
 /// <summary>
 /// Invoke or execute
 /// </summary>
 /// <param name="dispatcher">The dispatcher</param>
 /// <param name="action">Action object</param>
 public static void InvokeOrExecute(this System.Windows.Threading.Dispatcher dispatcher, Action action)
 {
     if (dispatcher.CheckAccess())
     {
         action();
     }
     else
     {
         dispatcher.BeginInvoke(DispatcherPriority.Normal, action);
     }
 }
示例#17
0
        public static void DoEvents(this System.Windows.Threading.Dispatcher dispatcher)
        {
            var frame = new DispatcherFrame();
            Action <DispatcherFrame> action = _ => { frame.Continue = false; };

            dispatcher.BeginInvoke(
                DispatcherPriority.SystemIdle,
                action,
                frame);
            Dispatcher.PushFrame(frame);
        }
        public CreateTournamentViewModel(Dispatcher dispatcher)
        {
            _dispatcher = dispatcher;
            _xmppHost = ((App)App.Current).XmppHost;
            _gameController = ServiceLocator.Current.GetInstance<GameController>();

            StartTournamentCommand = new RelayCommand(StartTournament);

            TournamentTypeListInternal.Add(new Option<string>("Round Robin", "RoundRobin"));
            _xmppHost.PlayerRegistered += (sender, e) => { _dispatcher.BeginInvoke(() => { RegisteredPlayerListInternal.Add(new Option<Jid>(e.User.Bare, e.User)); UpdateCanStartTournament(); }); };
        }
示例#19
0
        public void Download(string file, string saveWhere, Dispatcher dispatch, Action done)
        {
            var shareResp = _client.GetMedia(file);

            using (WebClient webclient = new WebClient())
            {
                webclient.DownloadFileCompleted +=
                    (object sender, AsyncCompletedEventArgs e) =>
                        { dispatch.BeginInvoke(new Action(() => { done(); })); };
                webclient.DownloadFileAsync(new Uri(shareResp.Url), saveWhere);
            }
        }
示例#20
0
        public static void OnUiThread(Action action, Dispatcher disp = null,
			DispatcherPriority prio = DispatcherPriority.Background)
        {
            if (disp == null)
            {
                if (Application.Current != null)
                    disp = Application.Current.Dispatcher;
            }

            if (disp != null)
                disp.BeginInvoke(action, prio);
        }
 public BuildItemViewModel(BuildItem item, Dispatcher dispatcher)
 {
     Item = item;
     Item.StatusChanged += (sender, args) => dispatcher.BeginInvoke((Action)(() =>
     {
         NotifyPropertyChanged("Status");
         NotifyPropertyChanged("Error");
         NotifyPropertyChanged("ErrorTitle");
         NotifyPropertyChanged("ErrorMessage");
         NotifyPropertyChanged("ShowError");
     }));
 }
 private void UpdateStats(RoutedEventArgs e)
 {
     var button = e.Source as Button;
     if (button != null)
     {
         _dispatcher = button.Dispatcher;
         var client = BrightstarService.GetClient(Store.Source.ConnectionString);
         _statsUpdateJob = client.UpdateStatistics(Store.Location);
         _dispatcher.BeginInvoke(DispatcherPriority.SystemIdle,
                                 new TransactionViewModel.JobMonitorDelegate(CheckJobStatus));
     }
 }
        protected MarginBase(IMarginSettings settings, ITextDocument document)
        {
            _dispatcher = Dispatcher.CurrentDispatcher;
            _settingsKey = document.TextBuffer.ContentType.DisplayName + "Margin_width";
            Document = document;
            Settings = settings;

            if (settings.ShowPreviewPane)
            {
                _dispatcher.BeginInvoke(
                    new Action(CreateMarginControls), DispatcherPriority.ApplicationIdle, null);
            }
        }
示例#24
0
        public static bool OnUIThreadAsync(Action action, DispatcherPriority priority = DispatcherPriority.Normal,
            Dispatcher dispatcher = null)
        {
            dispatcher = dispatcher ??
                         MainDispatcher ?? (Application.Current == null ? null : Application.Current.Dispatcher);
            if (dispatcher != null)
            {
                dispatcher.BeginInvoke(action, priority);
                return true;
            }

            return false;
        }
示例#25
0
 public static void ScrollToEnd(Dispatcher dispatcher, ListBox listBox)
 {
     if (dispatcher.CheckAccess())
     {
         SelectLastEntry(listBox);
     }
     else
     {
         dispatcher.BeginInvoke(
             DispatcherPriority.Send,
             new VoidFunctionHandler(SelectLastEntry),
             listBox);
     }
 }
示例#26
0
        /// <summary>
        /// Construct new application MainWindow.
        /// </summary>
        /// <param name="container"></param>
        /// <param name="dispatcher"></param>
        /// <param name="startTime"></param>
        public MainWindowViewModel(MembersContainer container, Dispatcher dispatcher, DateTime startTime)
        {
            SynchronizedMemberList.RefreshFinished += (s, e) => dispatcher.BeginInvoke(new Action<DateTime>(Compose), startTime);
            SynchronizedMemberList.RefreshFinished += (s, e) => SetTitle();
            SynchronizedMemberList.Initialize(container);

            this.ActiveDatabase = container;
            this.Dispatcher = dispatcher;

            this.TabPages = new ObservableCollection<ClosableViewModel>();
            this.TabPages.CollectionChanged += this.OnTabPagesChanged;

            ShowDefaultView();
        }
 public DataLoggerViewModel(PropellerSerialPort port) : base(port, typeof(IPropellerFrame))
 {
     ReadData = new System.Collections.ObjectModel.ObservableCollection<string>();
     uiDispatcher = Dispatcher.CurrentDispatcher;
     base.OnUpdated += delegate
     {
         if (base.StoreHistory)
         {
             uiDispatcher.BeginInvoke(DispatcherPriority.Background, new ThreadStart(() =>
             {
                 ReadData.Insert(0, string.Format("Received {0} : {1}", base.CurrentFrame.GetType().Name, base.CurrentFrame.ToString()));
             }));
         }
     };
 }
示例#28
0
        public void setTodoList(TodoList todoView)
        {
            this.todoView = todoView;
            todoView.todoListBox.ItemsSource = todoList;

            disp = Dispatcher.CurrentDispatcher;
            addToListFunction = (TodoListData todo) => disp.BeginInvoke(DispatcherPriority.Background, (new Action(() => {
                //System.Console.WriteLine(todo.description);
                TodoListBoxItem boxItem = new TodoListBoxItem(todo);
                todoList.Add(boxItem);
                todoListItems.Add(boxItem.getId, boxItem);
            })));

            updateTodoList();
        }
示例#29
0
        private void Run()
        {
            frame = new DispatcherFrame(true);

            dispatcher = Dispatcher.CurrentDispatcher;

            Action action = () =>
            {
                TaskFactory = new TaskFactory(TaskScheduler.FromCurrentSynchronizationContext());
                startedEvent.Set();
            };

            dispatcher.BeginInvoke(action);

            Dispatcher.PushFrame(frame);
        }
示例#30
0
 /// <summary>
 /// Processes all UI messages currently in the message queue.
 /// </summary>
 public static void DoEvents(Dispatcher dispatcher)
 {
     // Create new nested message pump.
     DispatcherFrame nestedFrame = new DispatcherFrame();
     // Dispatch a callback to the current message queue, when getting called,
     // this callback will end the nested message loop.
     // note that the priority of this callback should be lower than the that of UI event messages.
     DispatcherOperation exitOperation = dispatcher.BeginInvoke(
                                           DispatcherPriority.Background, exitFrameCallback, nestedFrame);
     // pump the nested message loop, the nested message loop will
     // immediately process the messages left inside the message queue.
     Dispatcher.PushFrame(nestedFrame);
     // If the "exitFrame" callback doesn't get finished, Abort it.
     if (exitOperation.Status != DispatcherOperationStatus.Completed)
         exitOperation.Abort();
 }
示例#31
0
 public void GetPeople(Dispatcher dispatcher)
 {
     IAddressBookService service = new AddressBookServiceClient();
     service.BeginGetPeople(delegate(IAsyncResult result)
     {
         ObservableCollection<Person> people = service.EndGetPeople(result);
         dispatcher.BeginInvoke(delegate
         {
             _people.Clear();
             foreach (Person person in people)
             {
                 _people.Add(person);
             }
         });
     }, null);
 }
示例#32
0
    public static void DoEvents( Dispatcher dispatcher )
    {
      if( dispatcher == null )
        throw new ArgumentNullException( "dispatcher" );

      DispatcherFrame nestedFrame = new DispatcherFrame();

      DispatcherOperation exitOperation = dispatcher.BeginInvoke( 
        DispatcherPriority.Background,
        DispatcherHelper.ExitFrameCallback,
        nestedFrame );

      Dispatcher.PushFrame( nestedFrame );

      if( exitOperation.Status != DispatcherOperationStatus.Completed )
        exitOperation.Abort();
    }
        public MarginBase(string source, string name, string contentType, bool showMargin, ITextDocument document)
        {
            Document = document;
            _marginName = name;
            _settingsKey = _marginName + "_width";
            _showMargin = showMargin;
            _dispatcher = Dispatcher.CurrentDispatcher;
            _provider = new ErrorListProvider(EditorExtensionsPackage.Instance);

            Document.FileActionOccurred += Document_FileActionOccurred;

            if (showMargin)
            {
                _dispatcher.BeginInvoke(
                    new Action(() => Initialize(contentType, source)), DispatcherPriority.ApplicationIdle, null);
            }
        }
 private void FitToBounds(System.Windows.Threading.Dispatcher dispatcher, ZoomControl zoom)
 {
     if (dispatcher != null)
     {
         dispatcher.BeginInvoke(new Action(()
                                           =>
         {
             zoom.ZoomToFill();
             zoom.Mode = ZoomControlModes.Custom;
             //zoom.FitToBounds();
         }), DispatcherPriority.Loaded);
     }
     else
     {
         zoom.ZoomToFill();
         zoom.Mode = ZoomControlModes.Custom;
     }
 }
示例#35
0
 private static Task RunAsync(Dispatcher dispatcher, Action action)
 {
     var completionSource = new TaskCompletionSource<object>();
     var dispatcherOperation = dispatcher.BeginInvoke(new Action(() =>
     {
         try
         {
             action();
         }
         catch (Exception ex)
         {
             completionSource.SetException(ex);
         }
     }), DispatcherPriority.Background);
     dispatcherOperation.Aborted += (s, e) => completionSource.SetCanceled();
     dispatcherOperation.Completed += (s, e) => completionSource.SetResult(null);
     return completionSource.Task;
 }
示例#36
0
        static WindowManager()
        {
            ChatWindows = new ConcurrentBag<ChatWindow>();
            GrowlWindow = new GrowlNotifications();
            _uiLagWindowThread = new Thread(() =>
            {
                _uiLagWindowDispatcher = Dispatcher.CurrentDispatcher;
                _uiLagWindowDispatcher.BeginInvoke(new Action(() =>
                {
                    UiLagWindow = new UiLagWindow();
                }));
                System.Windows.Threading.Dispatcher.Run();
            });

            _uiLagWindowThread.Name = "Lag Window UI Thread";
            _uiLagWindowThread.SetApartmentState(ApartmentState.STA);
            _uiLagWindowThread.Start();
        }
示例#37
0
    public FileModel(FileId id, ITextBuffer textBuffer, Server server, Dispatcher dispatcher, IVsHierarchy hierarchy, string fullPath)
    {
      Hierarchy   = hierarchy;
      FullPath    = fullPath;
      Id          = id;
      Server      = server;
      _textBuffer = textBuffer;

      var snapshot = textBuffer.CurrentSnapshot;
      var empty = new CompilerMessage[0];
      CompilerMessages          = new CompilerMessage[KindCount][] { empty,    empty,    empty };
      CompilerMessagesSnapshots = new ITextSnapshot[KindCount]     { snapshot, snapshot, snapshot };
      _errorListProviders       = new ErrorListProvider[KindCount] { null,     null,     null};


      server.Client.ResponseMap[id] = msg => dispatcher.BeginInvoke(DispatcherPriority.Normal,
        new Action<AsyncServerMessage>(msg2 => Response(msg2)), msg);

      server.Client.Send(new ClientMessage.FileActivated(id));
      textBuffer.Changed += TextBuffer_Changed;
    }
示例#38
0
            public void Invoke(object arg, params object[] args)
            {
                EventHandler method   = null;
                EventHandler handler2 = null;
                object       target   = this.Target;

                System.Windows.Threading.Dispatcher dispatcher = this.Dispatcher;
                if (!this.IsDisposable)
                {
                    if (this.IsDispatcherThreadAlive)
                    {
                        if (method == null)
                        {
                            method = delegate(object sender, EventArgs e)
                            {
                                this.handlerInfo.Invoke(target, new object[] { arg, e });
                            };
                        }
                        dispatcher.Invoke(DispatcherPriority.Send, method, arg, args);
                    }
                    else if (target is DispatcherObject)
                    {
                        if (handler2 == null)
                        {
                            handler2 = delegate(object sender, EventArgs e)
                            {
                                this.handlerInfo.Invoke(target, new object[] { arg, e });
                            };
                        }
                        dispatcher.BeginInvoke(DispatcherPriority.Send, handler2, arg, args);
                    }
                    else
                    {
                        ArrayList list = new ArrayList();
                        list.Add(arg);
                        list.AddRange(args);
                        this.handlerInfo.Invoke(target, list.ToArray());
                    }
                }
            }
示例#39
0
        private void LoadData(IEntityCollectionView <T> view)
        {
            #region query

            var requestId = ++RequestId;

            var query = Queryable.IncludeTotalCount();

            #endregion query

            #region paging

            if (view.PageSize > 0)
            {
                query = query
                        .Skip(view.PageIndex * view.PageSize)
                        .Take(view.PageSize);
            }

            #endregion pagging

            #region filters

            foreach (var filterExpression in view.FilterExpressions)
            {
                var remoteExpression = DataServiceQueryable.ToRemoteExpression(filterExpression);
                query = query.Where(remoteExpression);
            }

            #endregion filters

            #region sorting

            // apply sort descriptors
            IOrderedDataServiceQueryable <T, T> sortedQuery = null;
            foreach (var sortDescription in view.SortDescriptions)
            {
                var sortExpression = sortDescription.ToExpression <T>();
                if (ReferenceEquals(sortedQuery, null))
                {
                    sortedQuery = query.OrderBy(sortExpression);
                }
                else
                {
                    sortedQuery = sortedQuery.ThenBy(sortExpression);
                }
            }
            if (!ReferenceEquals(sortedQuery, null))
            {
                query = sortedQuery;
            }

            #endregion sorting

            #region request

            // notify data loading
            OnDataLoading();

            query.ExecuteAsync(
                (result) =>
            {
                if (requestId < RequestId)
                {
                    // request outdated
                    return;
                }

                // synchronize with main thread
                Dispatcher.BeginInvoke((Action) delegate
                {
                    // check for exception
                    if (result.IsFaulted)
                    {
                        var queryException = QueryException;
                        if (queryException != null)
                        {
                            queryException(this, new ExceptionEventArgs(result.Exception));
                            OnDataLoaded(null);
                            return;
                        }
                        else
                        {
                            throw new Exception("Query failed", result.Exception);
                        }
                    }

                    // retrieve data
                    var entitySet = result.EntitySet;

                    // fill items
                    view.Clear();
                    foreach (var item in entitySet)
                    {
                        view.Add(item);
                    }

                    // sets total count
                    view.TotalItemCount = entitySet.TotalCount.HasValue ? (int)entitySet.TotalCount.Value : -1;

                    // notify data loaded
                    OnDataLoaded(entitySet);
                });
            }
                );

            #endregion request
        }
示例#40
0
            private void MostrarInfor(int atraso, string link)
            {
                Dispatcher.BeginInvoke(new Action(() =>
                {
                    if (countTimeout != 0)
                    {
                        calc = (int)(listaTempo.Sum() + (listaTempo.Sum() * (countTimeout / 6)));
                    }
                    else
                    {
                        calc = listaTempo.Sum();
                    }


                    this.labelTempo.Content       = "Tempo: " + atraso + " ms ";
                    this.labelsemResposta.Content = "Sem resposta: " + countTotalTimeout;
                    this.labelpacotes.Content     = "Enviados: " + pacotesEnviado;
                    this.labelbytes.Content       = "Bytes: " + packetSize;

                    if (tag == "" || tag == " " || tag == "null" || tag == " null " || tag == "nulo" || tag == " nulo ")
                    {
                        labelnome.Content = "Servidor: " + link;
                    }
                    else
                    {
                        labelnome.Content = tag + link;
                    }

                    // Criando a rotação
                    RotateTransform myRotateTransform = new RotateTransform();
                    // Criando o grupo de rotação
                    TransformGroup myTransformGroup = new TransformGroup();


                    if ((listaTempo.Count == 5) && (((listaTempo.Sum() / listaTempo.Count) > 175) || (listaTempo.Sum() == 0)))
                    {
                        // Definindo a rotação
                        myRotateTransform.Angle = 175;

                        // Adicionando ao grupo de rotação
                        myTransformGroup.Children.Add(myRotateTransform);

                        // aplicando a rotação
                        indicador.RenderTransform = myTransformGroup;

                        if (this.limitePerdaVariavel == 1)
                        {
                            this.limitePerdaVariavel = 0;
                            EnProcesso = false;
                            MessageBox.Show("Verifique sua conexão com a internet! \n Falha ao conectar com o servidor! ");
                        }
                        else
                        {
                            this.limitePerdaVariavel += 1;
                        }
                    }
                    else if (listaTempo.Count > 5)
                    {
                        // resetando a lista e o countTimeout
                        listaTempo        = new System.Collections.Generic.List <int>();
                        this.countTimeout = 0;
                    }
                    else if (listaTempo.Count == 5)
                    {
                        // Definindo a rotação
                        myRotateTransform.Angle = calc / (listaTempo.Count - 1);

                        // adicionado o grupo de rotação
                        myTransformGroup.Children.Add(myRotateTransform);

                        // aplicando a rotação
                        indicador.RenderTransform = myTransformGroup;
                    }
                }));
            }
 private void thr_Change()
 {
     disp.BeginInvoke(DispatcherPriority.Normal, new changeDelegate(onChange));
 }
示例#42
0
 public void BeginInvoke(Action action)
 {
     _dispatcher.BeginInvoke(action);
 }
示例#43
0
 public static Op Async(this Disp dispatcher, Action action, params object[] args) =>
 dispatcher.BeginInvoke(action, args);
示例#44
0
 public static Task Run(this Disp dispatcher, Action action, params object[] args) =>
 dispatcher.BeginInvoke(action, args).Task;
示例#45
0
 public static DispatcherOperation BeginInvoke(this Dispatcher dispatcher, Action action)
 {
     return(dispatcher.BeginInvoke(action));
 }
示例#46
0
 public static DispatcherOperation BeginInvoke(this Dispatcher dispatcher, Action action, DispatcherPriority priority)
 {
     return(dispatcher.BeginInvoke(action, priority));
 }
示例#47
0
        /// <summary>
        /// 動画ファイル検索&タグ情報取得
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SearchTarget_DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker bw = (BackgroundWorker)sender;
            var targetDir       = (string)e.Argument;

            var mp4wd      = new MP4WebDriver();
            var resultList = mp4wd.GetTagInfo(targetDir, bw);

            //グリッドに表示
            _dispatcher.BeginInvoke(new Action(() => {
                this.TargetGrid.Rows.Count = RowHeaderCount;

                var bu = new BitmapUtil();
                this.TargetGrid.Rows.Count = resultList.Count + RowHeaderCount;
                this.DenominatorLabel.Text = resultList.Count.ToString() + "件";
                int i = RowHeaderCount;
                foreach (var row in resultList)
                {
                    var fi = row.Key;
                    var ti = row.Value;

                    //対象
                    if (StringUtil.NullToBlank(ti.Title) != "")
                    {
                        this.TargetGrid[i, (int)ColIndex.TargetCheck] = true;
                        this.TargetGrid.Rows[i].AllowEditing          = true;
                        this.TargetGrid[i, (int)ColIndex.Status]      = EnumUtil.GetLabel(StatusEnum.Avairable);
                    }
                    else
                    {
                        this.TargetGrid[i, (int)ColIndex.TargetCheck] = false;
                        this.TargetGrid.Rows[i].AllowEditing          = false;
                        this.TargetGrid.Rows[i].StyleNew.BackColor    = Color.Gainsboro;
                        this.TargetGrid[i, (int)ColIndex.Status]      = EnumUtil.GetLabel(StatusEnum.UnAvairable);
                    }
                    //ファイルアイコン
                    Bitmap bmp = null;
                    bmp        = Properties.Resources.File16;
                    try {
                        bmp = Icon.ExtractAssociatedIcon(fi.FullName).ToBitmap();
                    } catch {
                        //プレビューを取得できない場合は、デフォルトアイコンを表示
                    }
                    bmp.MakeTransparent();
                    this.TargetGrid.SetCellImage(i, (int)ColIndex.FileIcon, bu.Resize(bmp, 16, 16));
                    //ファイル名
                    this.TargetGrid[i, (int)ColIndex.FileName]   = fi.Name;
                    this.TargetGrid[i, (int)ColIndex.FullPath]   = fi.FullName;
                    this.TargetGrid[i, (int)ColIndex.Extension]  = fi.Extension;
                    this.TargetGrid[i, (int)ColIndex.UpdateDate] = fi.LastWriteTime;
                    //タグ情報
                    this.TargetGrid[i, (int)ColIndex.Title]       = StringUtil.NullToBlank(ti.Title);
                    this.TargetGrid[i, (int)ColIndex.ReleaseDate] = StringUtil.NullToBlank(ti.ReleaseDate);
                    this.TargetGrid[i, (int)ColIndex.Artist]      = StringUtil.NullToBlank(ti.Performers);
                    this.TargetGrid[i, (int)ColIndex.Genres]      = StringUtil.NullToBlank(ti.Genres);
                    this.TargetGrid[i, (int)ColIndex.Maker]       = StringUtil.NullToBlank(ti.Maker);
                    this.TargetGrid[i, (int)ColIndex.Director]    = StringUtil.NullToBlank(ti.Director);
                    this.TargetGrid[i, (int)ColIndex.Comment]     = StringUtil.NullToBlank(ti.Comment);
                    this.TargetGrid[i, (int)ColIndex.PageUrl]     = StringUtil.NullToBlank(ti.PageUrl);
                    this.TargetGrid[i, (int)ColIndex.ImageUrl]    = StringUtil.NullToBlank(ti.ImageUrl);
                    this.TargetGrid.SetCellImage(i, (int)ColIndex.Image, bu.GetBitmapFromURL(ti.ImageUrl));

                    i++;
                }
                //先頭行を選択
                if (this.TargetGrid.Rows.Count > RowHeaderCount)
                {
                    this.TargetGrid.Select(RowHeaderCount, (int)ColIndex.TargetCheck);
                }
            }));
        }
示例#48
-1
        public ConnectionManager(Dispatcher dispatcher)
        {
            _dispatcher = dispatcher;
#pragma warning disable 168
            const string localUrl = "http://localhost:20449/";
            const string remoteUrl = "http://192.168.10.42:8082/";
#pragma warning restore 168
            var hub = new HubConnection(remoteUrl);


            _gameHub = hub.CreateProxy("GameHub");
            _gameHub.On<string>("addMessage", ProcessMessage);
            _gameHub.On<int, int, int>("lineClicked", HandleLineClicked);
            _gameHub.On<Player>("newPlayerJoined", HandleNewPlayerJoined);
            _gameHub.On<GameState>("resetGame", HandleResetGame);
            _gameHub.On<Player>("playerLeft", HandlePlayerLeft);
            _gameHub.On<GameState>("addedToGame", HandleAddedToGame);

            hub.Start().ContinueWith(delegate
                                         {
                                             if (Started != null)
                                                 _dispatcher.BeginInvoke(() => Started(this, new EventArgs()));
                                         }
                );
        }