コード例 #1
0
ファイル: Dispatcher.cs プロジェクト: kaagati/spectre
 public void InvokeAsync(Action action, DispatcherQueue queue = DispatcherQueue.Renderer)
 {
     var task = new Task(action);
     task.Executed += OnExecuted;
     CefTaskCapi.CefPostTask((CefThreadId) queue, task.Handle);
     lock (_mutex) {
         _tasks.Add(task);
     }
 }
コード例 #2
0
        static WcfProcessingClient()
        {         
#if DEBUG
            //   Microsoft.Research.Science.Data.Factory.DataSetFactory.Register(typeof(Microsoft.Research.Science.Data.Memory.MemoryDataSet));
            //Microsoft.Research.Science.Data.Factory.DataSetFactory.Register(
            //    typeof(Microsoft.Research.Science.Data.CSV.CsvDataSet));
            //Microsoft.Research.Science.Data.Factory.DataSetFactory.Register(
            //    typeof(Microsoft.Research.Science.Data.Proxy.WCF.WcfDataSetFactory));
            //Console.WriteLine(Microsoft.Research.Science.Data.Factory.DataSetFactory.RegisteredToString());
#endif
            taskQueue = new DispatcherQueue("ClimateServiceClient", dispatcher);
        }
コード例 #3
0
 /// <summary>
 /// Initializes a new instance of the <see cref="RemoteDeviceHelper"/> class.
 /// </summary>
 /// <param name="filter">Initiate Enumeration with specific RemoteSystemKind with Filters</param>
 /// <param name="dispatcherQueue">The DispatcherQueue that should be used to dispatch UI updates, or null if this is being called from the UI thread.</param>
 public RemoteDeviceHelper(List <IRemoteSystemFilter> filter, DispatcherQueue dispatcherQueue = null)
 {
     DispatcherQueue = dispatcherQueue ?? DispatcherQueue.GetForCurrentThread();
     RemoteSystems   = new ObservableCollection <RemoteSystem>();
     GenerateSystemsWithFilterAsync(filter);
 }
コード例 #4
0
 public void Init() => Dispatcher = DispatcherQueue.GetForCurrentThread();
コード例 #5
0
 public void Test_DispatcherQueueHelper_FuncOfT_Null()
 {
     DispatcherQueue.GetForCurrentThread().EnqueueAsync(default(Func <int>) !);
 }
コード例 #6
0
        public FolderProperties(SelectedItemsPropertiesViewModel viewModel, CancellationTokenSource tokenSource, DispatcherQueue coreDispatcher, ListedItem item, IShellPage instance)
        {
            ViewModel   = viewModel;
            TokenSource = tokenSource;
            Dispatcher  = coreDispatcher;
            Item        = item;
            AppInstance = instance;

            GetBaseProperties();
            ViewModel.PropertyChanged += ViewModel_PropertyChanged;
        }
コード例 #7
0
        /// <summary>
        /// Service start
        /// </summary>
        protected override void Start()
        {
            //
            // Add service specific initialization here
            //

            base.Start();
            int exampleNum = 3;

            switch (exampleNum)
            {
            case 1:
                // Create port that accepts instances of System.Int32
                Port <int> portInt1 = new Port <int>();

                // Add the number 10 to the port
                portInt1.Post(10);

                // Display number of items to the console
                Console.WriteLine(portInt1.ItemCount);
                break;

            case 2:
                // Create port that accepts instances of System.Int32
                var portInt2 = new Port <int>();

                // Add the number 10 to the port
                portInt2.Post(10);

                // Display number of items to the console
                Console.WriteLine(portInt2.ItemCount);

                // retrieve the item using Test
                int item2;
                var hasItem2 = portInt2.Test(out item2);
                if (hasItem2)
                {
                    Console.WriteLine("Found item in port:" + item2);
                }
                portInt2.Post(11);
                // alternative to using Test is just assignment of port to variable using
                // implicit operator
                var nextItem = portInt2;

                Console.WriteLine("Found item in port:" + nextItem);
                break;

            case 3:
                // Create port that accepts instances of System.Int32
                var portInt3 = new Port <int>();

                // Add the number 10 to the port
                portInt3.Post(10);

                // Display number of items to the console
                Console.WriteLine(portInt3.ItemCount);

                // create dispatcher and dispatcher queue for scheduling tasks
                Dispatcher      dispatcher = new Dispatcher();
                DispatcherQueue taskQueue  = new DispatcherQueue("sample queue", dispatcher);

                // retrieve the item by attaching a one time receiver
                Arbiter.Activate(
                    taskQueue,
                    portInt3.Receive(delegate(int item3)     // anonymous method
                {
                    // this code executes in parallel with the method that
                    // activated it
                    Console.WriteLine("Received item:" + item3);
                }
                                     ));
                // any code below runs in parallel with delegate

                break;

            case 4:
                // Create a PortSet using generic type arguments
                var genericPortSet4 = new PortSet <int, string, double>();
                genericPortSet4.Post(10);
                genericPortSet4.Post("hello");
                genericPortSet4.Post(3.14159);

                // Create a runtime PortSet, using the initialization
                // constructor to supply an array of types
                PortSet runtimePortSet4 = new PortSet(
                    typeof(int),
                    typeof(string),
                    typeof(double)
                    );

                runtimePortSet4.PostUnknownType(10);
                runtimePortSet4.PostUnknownType("hello");
                runtimePortSet4.PostUnknownType(3.14159);
                break;

            case 5:
                // create dispatcher and dispatcher queue for scheduling tasks
                Dispatcher      dispatcher5 = new Dispatcher();
                DispatcherQueue taskQueue5  = new DispatcherQueue("sample queue", dispatcher5);
                CcrConsolePort  port5       = CcrConsoleService.Create(taskQueue5);
                break;

            case 6:
                Dispatcher      dispatcher6 = new Dispatcher();
                DispatcherQueue taskQueue6  = new DispatcherQueue("sample queue", dispatcher6);
                CcrConsolePort  port6       = CcrConsoleService.Create(taskQueue6);
                var             portSet6    = new PortSet <int, string, double>();
                // the following statement compiles because of the implicit assignment operators
                // that "extract" the instance of Port<int> from the PortSet
                var portInt6 = portSet6;

                // the implicit assignment operator is used below to "extract" the Port<int>
                // instance so the int receiver can be registered
                Arbiter.Activate(taskQueue6,
                                 Arbiter.Receive <int>(true, portSet6, item => Console.WriteLine(item))
                                 );

                break;

            case 7:
                Dispatcher      dispatcher7 = new Dispatcher();
                DispatcherQueue taskQueue7  = new DispatcherQueue("sample queue", dispatcher7);
                var             port7       = new Port <int>();
                Arbiter.Activate(taskQueue7,
                                 Arbiter.Receive(
                                     true,
                                     port7,
                                     item => Console.WriteLine(item)

                                     /** older syntax
                                      *    delegate(int item){
                                      *        Console.WriteLine(item);
                                      *    }
                                      *
                                      **/

                                     )
                                 );

                // post item, so delegate executes
                port7.Post(5);
                break;

            case 8:
                Dispatcher      dispatcher8 = new Dispatcher();
                DispatcherQueue taskQueue8  = new DispatcherQueue("sample queue", dispatcher8);
                var             port8       = new Port <int>();
                // alternate version that explicitly constructs a Receiver by passing
                // Arbiter class factory methods
                var persistedReceiver = new Receiver <int>(
                    true,                                           // persisted
                    port8,
                    null,                                           // no predicate
                    new Task <int>(item => Console.WriteLine(item)) // task to execute
                    );
                Arbiter.Activate(taskQueue8, persistedReceiver);
                break;

            case 9:
                Dispatcher      dispatcher9 = new Dispatcher();
                DispatcherQueue taskQueue9  = new DispatcherQueue("sample queue", dispatcher9);
                // create a simple service listening on a port
                ServicePort servicePort9 = SimpleService.Create(taskQueue9);

                // create request
                GetState get = new GetState();

                // post request
                servicePort9.Post(get);

                // use the extension method on the PortSet that creates a choice
                // given two types found on one PortSet. This a common use of
                // Choice to deal with responses that have success or failure
                Arbiter.Activate(taskQueue9,
                                 get.ResponsePort.Choice(
                                     s => Console.WriteLine(s),  // delegate for success
                                     ex => Console.WriteLine(ex) // delegate for failure
                                     ));
                break;

            case 10:
                Dispatcher      dispatcher10 = new Dispatcher();
                DispatcherQueue taskQueue10  = new DispatcherQueue("sample queue", dispatcher10);
                var             portDouble   = new Port <double>();
                var             portString   = new Port <string>();

                // activate a joined receiver that will execute only when one
                // item is available in each port.
                Arbiter.Activate(taskQueue10,
                                 portDouble.Join(
                                     portString,             // port to join with
                                     (value, stringValue) => // delegate
                {
                    value      /= 2.0;
                    stringValue = value.ToString();
                    // post back updated values
                    portDouble.Post(value);
                    portString.Post(stringValue);
                })
                                 );

                // post items. The order does not matter, which is what Join its power
                portDouble.Post(3.14159);
                portString.Post("0.1");

                //after the last post the delegate above will execute
                break;
            }
        }
コード例 #8
0
 public MainPage()
 {
     InitializeComponent();
     _dispatcherQueue = DispatcherQueue.GetForCurrentThread();
     image.Source     = new SoftwareBitmapSource();
 }
コード例 #9
0
ファイル: Dispatcher.cs プロジェクト: kaagati/spectre
 public void InvokeAsync(Action action, DispatcherQueue queue, TimeSpan delay)
 {
     var task = new Task(action);
     CefTaskCapi.CefPostDelayedTask((CefThreadId) queue, task.Handle, (long) delay.TotalMilliseconds);
 }
 /// <summary>
 /// When the Characteristics value changes.
 /// </summary>
 /// <param name="sender">The sender.</param>
 /// <param name="args">The <see cref="GattValueChangedEventArgs"/> instance containing the event data.</param>
 private async void Characteristic_ValueChanged(GattCharacteristic sender, GattValueChangedEventArgs args)
 {
     await DispatcherQueue.EnqueueAsync(() => { SetValue(args.CharacteristicValue); }, DispatcherQueuePriority.Normal);
 }
        /// <summary>
        /// Initializes a new instance of the <see cref="ObservableGattCharacteristics"/> class.
        /// </summary>
        /// <param name="characteristic">The characteristic.</param>
        /// <param name="parent">The parent.</param>
        /// <param name="dispatcherQueue">The DispatcherQueue that should be used to dispatch UI updates, or null if this is being called from the UI thread.</param>
        public ObservableGattCharacteristics(GattCharacteristic characteristic, ObservableGattDeviceService parent, DispatcherQueue dispatcherQueue = null)
        {
            DispatcherQueue = dispatcherQueue ?? DispatcherQueue.GetForCurrentThread();

            Characteristic = characteristic;
            Parent         = parent;
            Name           = GattUuidsService.ConvertUuidToName(Characteristic.Uuid);
            UUID           = Characteristic.Uuid.ToString();

#pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
            ReadValueAsync();
#pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed

            characteristic.ValueChanged += Characteristic_ValueChanged;
        }
コード例 #12
0
 private void Geoline_TargetVisibilityChanged(object sender, EventArgs e)
 {
     // This is needed because Runtime delivers notifications from a different thread that doesn't have access to UI controls.
     DispatcherQueue.TryEnqueue(Microsoft.UI.Dispatching.DispatcherQueuePriority.Normal, UpdateUiAndSelection);
 }
コード例 #13
0
 public BackgroundDownloadService()
 {
     _cts             = new CancellationTokenSource();
     _dispatcherQueue = DispatcherQueue.GetForCurrentThread();
 }
コード例 #14
0
ファイル: Dispatcher.cs プロジェクト: kaagati/spectre
 public bool IsCurrentlyOn(DispatcherQueue queue)
 {
     var result = CefTaskCapi.CefCurrentlyOn((CefThreadId) queue);
     return Convert.ToBoolean(result);
 }
コード例 #15
0
        /// <summary>
        /// Initializes a new instance of the <see cref="PrintHelper"/> class.
        /// </summary>
        /// <param name="canvasContainer">XAML panel used to attach printing canvas. Can be hidden in your UI with Opacity = 0 for instance</param>
        /// <param name="defaultPrintHelperOptions">Default settings for the print tasks</param>
        /// <param name="dispatcherQueue">The DispatcherQueue that should be used to dispatch UI updates, or null if this is being called from the UI thread.</param>
        public PrintHelper(Panel canvasContainer, PrintHelperOptions defaultPrintHelperOptions = null, DispatcherQueue dispatcherQueue = null)
        {
            DispatcherQueue = dispatcherQueue ?? DispatcherQueue.GetForCurrentThread();

            if (canvasContainer == null)
            {
                throw new ArgumentNullException();
            }

            _printPreviewPages   = new List <FrameworkElement>();
            _printCanvas         = new Canvas();
            _printCanvas.Opacity = 0;

            _canvasContainer = canvasContainer;
            _canvasContainer.RequestedTheme = ElementTheme.Light;

            _elementsToPrint = new List <FrameworkElement>();

            _defaultPrintHelperOptions = defaultPrintHelperOptions ?? new PrintHelperOptions();

            RegisterForPrinting();
        }
コード例 #16
0
 public TimerService()
 {
     _dispatcherQueue = DispatcherQueue.GetForCurrentThread();
     _timer           = new Timer();
     _timer.Elapsed  += TimerIntervalElapsed;
 }
コード例 #17
0
        static void ParallelIntegration(dynamic step, dynamic Low, dynamic Up, ScriptScope scope)
        {
            // создание массива объектов для хранения параметров
            InputData[] ClArr = new InputData[nc];
            for (int i = 0; i < nc; i++)
            {
                ClArr[i] = new InputData();
            }

            //Далее, задаются исходные данные для каждого экземпляра
            //вычислительного метода:
            // заполняем массив параметров
            dynamic Low_temp = Low;

            for (int i = 0; i < nc; i++)
            {
                ClArr[i].start = Low_temp;
                if (i + 1 == nc)
                {
                    ClArr[i].stop = Up;
                }
                else
                {
                    ClArr[i].stop = Low_temp + step;
                }

                Low_temp = Low_temp + step;
            }
            //Создаётся диспетчер с пулом из двух потоков:
            Dispatcher      d  = new Dispatcher(nc, "Test Pool");
            DispatcherQueue dq = new DispatcherQueue("Test Queue", d);
            //Описывается порт, в который каждый экземпляр метода Int()
            //отправляет сообщение после завершения вычислений:
            Port <int> p = new Port <int>();

            //Метод Arbiter.Activate помещает в очередь диспетчера две задачи(два
            //экземпляра метода Mul):

            System.Diagnostics.Stopwatch ssWatch = new System.Diagnostics.Stopwatch();
            ssWatch.Start();

            for (int i = 0; i < nc; i++)
            {
                Arbiter.Activate(dq, new Task <InputData, Port <int>, ScriptScope>(ClArr[i], p, scope, Int));
            }
            //Первый параметр метода Arbiter.Activate – очередь диспетчера,
            //который будет управлять выполнением задачи, второй параметр –
            //запускаемая задача.
            //С помощью метода Arbiter.MultipleItemReceive запускается задача
            //(приёмник), которая обрабатывает получение двух сообщений портом p:
            Arbiter.Activate(dq, Arbiter.MultipleItemReceive(true, p, nc, delegate(int[] array)
            {
                Console.WriteLine("Вычисления завершены");
                ssWatch.Stop();
                Console.WriteLine("Полное время работы {0} мс", ssWatch.ElapsedMilliseconds.ToString());
                Console.ReadKey(true);
                Environment.Exit(0);
            }));



            Console.ReadKey(true);
            Environment.Exit(0);
        }
コード例 #18
0
ファイル: ColorElement.cs プロジェクト: nmoschkin/DataTools5
        private void RenderPicker(int w = 0, int h = 0)
        {
            if (_container == null)
            {
                return;
            }

            double width  = w > 0 ? w : this.Width;
            double height = h > 0 ? h : this.Height;

            if (width == -1 || height == -1)
            {
                return;
            }

            double colorVal = this.ColorValue;
            double offset   = this.HueOffset;
            bool   invert   = this.InvertSaturation;
            float  esize    = this.ElementSize;

            ColorPickerMode mode = this.Mode;

            _ = Task.Run(() =>
            {
                ColorPickerRenderer cw;

                if (w <= 0)
                {
                    if (double.IsNaN(width))
                    {
                        return;
                    }
                    w = (int)width;
                }
                if (h <= 0)
                {
                    if (double.IsNaN(height))
                    {
                        return;
                    }
                    h = (int)height;
                }

                if (w < 32 || h < 32)
                {
                    return;
                }

                if (mode == ColorPickerMode.Wheel || mode == ColorPickerMode.HexagonWheel)
                {
                    int rad;

                    if (h < w)
                    {
                        rad = h / 2;
                        w   = h;
                    }
                    else
                    {
                        rad = w / 2;
                        h   = w;
                    }

                    cw = new ColorPickerRenderer(rad, colorVal, offset, invert, true);
                }
                else
                {
                    cw = new ColorPickerRenderer(w, h, colorVal, offset, invert, mode == ColorPickerMode.LinearVertical, true);
                }

                DispatcherQueue.TryEnqueue(async() =>
                {
                    SKImage img;
                    SKBitmap bmp = new SKBitmap((int)cw.Bounds.Width, (int)cw.Bounds.Height, SKColorType.Bgra8888, SKAlphaType.Premul);

                    var ptr = bmp.GetPixels();

                    unsafe
                    {
                        var gch = GCHandle.Alloc(cw.ImageBytes, GCHandleType.Pinned);

                        Buffer.MemoryCopy((void *)gch.AddrOfPinnedObject(), (void *)ptr, cw.ImageBytes.Length, cw.ImageBytes.Length);
                        gch.Free();
                    }

                    bmp.SetImmutable();
                    img = SKImage.FromBitmap(bmp);

                    SKData encoded = img.Encode();
                    Stream stream  = encoded.AsStream();

                    //var ret = ImageSource.FromStream(() => stream);

                    cpRender = cw;


                    Compositor _compositor = _container.Compositor;
                    SpriteVisual _imageVisual;
                    CompositionSurfaceBrush _imageBrush;

                    _imageBrush = _compositor.CreateSurfaceBrush();

                    // The loadedSurface has a size of 0x0 till the image has been been downloaded, decoded and loaded to the surface. We can assign the surface to the CompositionSurfaceBrush and it will show up once the image is loaded to the surface.
                    LoadedImageSurface _loadedSurface = LoadedImageSurface.StartLoadFromStream(stream.AsRandomAccessStream());

                    _imageBrush.Surface = _loadedSurface;

                    _imageVisual       = _compositor.CreateSpriteVisual();
                    _imageVisual.Brush = _imageBrush;
                    _imageVisual.Size  = new Vector2(cw.Bounds.Width, cw.Bounds.Height);
                    //_imageVisual.Offset = new Vector3((float)Padding.Left, (float)Padding.Top, 0);

                    _container.Children.RemoveAll();
                    _container.Children.InsertAtBottom(_imageVisual);

                    currentShape  = null;
                    currentSprite = null;
                    currentGeo    = null;
                });
            });
        }
コード例 #19
0
        private async void TokenizingTextBox_CharacterReceived(UIElement sender, CharacterReceivedRoutedEventArgs args)
        {
            var container = ContainerFromItem(_currentTextEdit) as TokenizingTextBoxItem;

            if (container != null && !(GetFocusedElement().Equals(container._autoSuggestTextBox) || char.IsControl(args.Character)))
            {
                if (SelectedItems.Count > 0)
                {
                    var index = _innerItemsSource.IndexOf(SelectedItems.First());

                    await RemoveAllSelectedTokens();

                    // Wait for removal of old items
                    var dispatcherQueue = DispatcherQueue.GetForCurrentThread();
                    _ = dispatcherQueue.EnqueueAsync(
                        () =>
                    {
                        // If we're before the last textbox and it's empty, redirect focus to that one instead
                        if (index == _innerItemsSource.Count - 1 && string.IsNullOrWhiteSpace(_lastTextEdit.Text))
                        {
                            var lastContainer = ContainerFromItem(_lastTextEdit) as TokenizingTextBoxItem;

                            lastContainer.UseCharacterAsUser = true;     // Make sure we trigger a refresh of suggested items.

                            _lastTextEdit.Text = string.Empty + args.Character;

                            UpdateCurrentTextEdit(_lastTextEdit);

                            lastContainer._autoSuggestTextBox.SelectionStart = 1;     // Set position to after our new character inserted

                            lastContainer._autoSuggestTextBox.Focus(FocusState.Keyboard);
                        }
                        else
                        {
                            //// Otherwise, create a new textbox for this text.

                            UpdateCurrentTextEdit(new PretokenStringContainer((string.Empty + args.Character).Trim()));     // Trim so that 'space' isn't inserted and can be used to insert a new box.

                            _innerItemsSource.Insert(index, _currentTextEdit);

                            // Need to wait for containerization
                            _ = dispatcherQueue.EnqueueAsync(
                                () =>
                            {
                                var newContainer = ContainerFromIndex(index) as TokenizingTextBoxItem; // Should be our last text box

                                newContainer.UseCharacterAsUser = true;                                // Make sure we trigger a refresh of suggested items.

                                void WaitForLoad(object s, RoutedEventArgs eargs)
                                {
                                    if (newContainer._autoSuggestTextBox != null)
                                    {
                                        newContainer._autoSuggestTextBox.SelectionStart = 1;         // Set position to after our new character inserted

                                        newContainer._autoSuggestTextBox.Focus(FocusState.Keyboard);
                                    }

                                    newContainer.Loaded -= WaitForLoad;
                                }

                                newContainer.AutoSuggestTextBoxLoaded += WaitForLoad;
                            }, DispatcherQueuePriority.Normal);
                        }
                    }, DispatcherQueuePriority.Normal);
                }
                else
                {
                    // If no items are selected, send input to the last active string container.
                    // This code is only fires during an edgecase where an item is in the process of being deleted and the user inputs a character before the focus has been redirected to a string container.
                    if (_innerItemsSource[_innerItemsSource.Count - 1] is ITokenStringContainer textToken)
                    {
                        var last           = ContainerFromIndex(Items.Count - 1) as TokenizingTextBoxItem; // Should be our last text box
                        var text           = last._autoSuggestTextBox.Text;
                        var selectionStart = last._autoSuggestTextBox.SelectionStart;
                        var position       = selectionStart > text.Length ? text.Length : selectionStart;
                        textToken.Text = text.Substring(0, position) + args.Character +
                                         text.Substring(position);

                        last._autoSuggestTextBox.SelectionStart = position + 1; // Set position to after our new character inserted

                        last._autoSuggestTextBox.Focus(FocusState.Keyboard);
                    }
                }
            }
        }
コード例 #20
0
 internal PrintHelperStateBag(DispatcherQueue dispatcherQueue)
 {
     _dispatcherQueue = dispatcherQueue;
 }
 private static async void RunInUIThread(DispatcherQueue dispatcherQueue, Action action)
 {
     await dispatcherQueue.ExecuteOnUIThreadAsync(action, DispatcherQueuePriority.Normal);
 }
コード例 #22
0
        private void Frame_Navigated(object sender, Windows.UI.Xaml.Navigation.NavigationEventArgs e)
        {
            var navigatedPage = (sender as Frame).Content as Page;

            if (navigatedPage == null)
            {
                return;
            }

            void LoadedHandler(object s, RoutedEventArgs args)
            {
                var page = s as Page;

                page.Loaded -= LoadedHandler;

                object parameter;

                if (_nextParameter != null)
                {
                    parameter = _nextParameter;
                }
                else if (e.NavigationMode == Windows.UI.Xaml.Navigation.NavigationMode.Back)
                {
                    var sourcePage = (sender as Frame).ForwardStack.LastOrDefault();
                    parameter = sourcePage?.Parameter;
                }
                else
                {
                    parameter = e.Parameter;
                }

                var cas = ConnectedAnimationService.GetForCurrentView();

                var connectedAnimationsProps     = Connected.GetPageConnectedAnimationProperties(page);
                var coordinatedAnimationElements = Connected.GetPageCoordinatedAnimationElements(page);

                foreach (var props in connectedAnimationsProps.Values)
                {
                    var connectedAnimation = cas.GetAnimation(props.Key);
                    var animationHandled   = false;
                    if (connectedAnimation != null)
                    {
                        if (props.IsListAnimation && parameter != null)
                        {
                            foreach (var listAnimProperty in props.ListAnimProperties)
                            {
                                if (listAnimProperty.ListViewBase.ItemsSource is IEnumerable <object> items && items.Contains(parameter))
                                {
                                    listAnimProperty.ListViewBase.ScrollIntoView(parameter);

                                    // give time to the UI thread to scroll the list
                                    var dispatcherQueue = DispatcherQueue.GetForCurrentThread();
                                    var t = dispatcherQueue.EnqueueAsync(
                                        async() =>
                                    {
                                        try
                                        {
                                            var success = await listAnimProperty.ListViewBase.TryStartConnectedAnimationAsync(connectedAnimation, parameter, listAnimProperty.ElementName);
                                        }
                                        catch (Exception)
                                        {
                                            connectedAnimation.Cancel();
                                        }
                                    }, DispatcherQueuePriority.Normal);

                                    animationHandled = true;
                                }
                            }
                        }
                        else if (!props.IsListAnimation)
                        {
                            if (coordinatedAnimationElements.TryGetValue(props.Element, out var coordinatedElements))
                            {
                                connectedAnimation.TryStart(props.Element, coordinatedElements);
                            }
                            else
                            {
                                connectedAnimation.TryStart(props.Element);
                            }

                            animationHandled = true;
                        }
                    }

                    if (_previousPageConnectedAnimationProps.ContainsKey(props.Key) && animationHandled)
                    {
                        _previousPageConnectedAnimationProps.Remove(props.Key);
                    }
                }

                // if there are animations that were prepared on previous page but no elements on this page have the same key - cancel
                foreach (var previousProps in _previousPageConnectedAnimationProps)
                {
                    var connectedAnimation = cas.GetAnimation(previousProps.Key);
                    connectedAnimation?.Cancel();
                }

                _previousPageConnectedAnimationProps.Clear();
                _nextParameter = null;
            }

            navigatedPage.Loaded += LoadedHandler;
        }
コード例 #23
0
ファイル: RSUtils.cs プロジェクト: yingted/Myro
 /// <summary>
 /// Synchronous receive.
 /// Waits for a response, returning T on success, and throwing an
 /// exception created by ExceptionOfFault on failure.
 /// </summary>
 /// <typeparam name="T"></typeparam>
 /// <param name="port"></param>
 /// <returns></returns>
 public static T ReceiveSync <T>(DispatcherQueue taskQueue, PortSet <T, Fault> port)
 {
     return(ReceiveSync(taskQueue, port, Params.DefaultRecieveTimeout));
 }
コード例 #24
0
 public void Test_DispatcherQueueHelper_Action_Null()
 {
     DispatcherQueue.GetForCurrentThread().EnqueueAsync(default(Action) !);
 }
コード例 #25
0
        public EntityUIForm(DispatcherQueue dispatcherQueue)
        {
            InitializeComponent();

            _dispatcherQueue = dispatcherQueue;
        }
コード例 #26
0
 internal Dispatcher(DispatcherQueue dispatcherQueue)
 {
     _dispatcherQueue = dispatcherQueue ?? throw new ArgumentNullException(nameof(dispatcherQueue));
 }
コード例 #27
0
 private void Update()
 {
     DispatcherQueue.DequeueAndExecute();
 }
コード例 #28
0
 /// <summary>
 /// Initializes a new instance of the <see cref="RemoteDeviceHelper"/> class.
 /// </summary>
 /// <param name="dispatcherQueue">The DispatcherQueue that should be used to dispatch UI updates, or null if this is being called from the UI thread.</param>
 public RemoteDeviceHelper(DispatcherQueue dispatcherQueue = null)
 {
     DispatcherQueue = dispatcherQueue ?? DispatcherQueue.GetForCurrentThread();
     RemoteSystems   = new ObservableCollection <RemoteSystem>();
     GenerateSystems();
 }
コード例 #29
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ImageCache"/> class.
 /// </summary>
 /// <param name="dispatcherQueue">The DispatcherQueue that should be used to dispatch UI updates, or null if this is being called from the UI thread.</param>
 public ImageCache(DispatcherQueue dispatcherQueue = null)
 {
     DispatcherQueue = dispatcherQueue ?? DispatcherQueue.GetForCurrentThread();
     _extendedPropertyNames.Add(DateAccessedProperty);
 }
コード例 #30
0
 public KeyboardListener(CodeEditor parent, DispatcherQueue queue) // TODO: Make Interface for event usage
 {
     this.parent = new WeakReference <CodeEditor>(parent);
     _queue      = queue;
 }
コード例 #31
0
        internal void ReloadConfig(RelayNodeConfig newConfiguration)
        {
            if (newConfiguration != null)
            {
                if (log.IsInfoEnabled)
                {
                    log.Info("Reloading configs.");
                }

                fatalFailureTimeout = newConfiguration.FatalShutdownTimeout < 0
                                        ? TimeSpan.FromMinutes(5)
                                        : TimeSpan.FromSeconds(newConfiguration.FatalShutdownTimeout);

                if (newConfiguration.GetMyNode() != null)
                {
                    MyZone = newConfiguration.GetMyNode().Zone;
                }

                SetClusterAddresses(newConfiguration);

                messageTracer.ReloadConfig(newConfiguration.TypeSettings.MaxTypeId, newConfiguration.TraceSettings);
                messageTracer.Activated = newConfiguration.OutputTraceInfo;

                //TODO: handle changes in component definition
                components.ReloadConfig(newConfiguration, newConfiguration.IgnoredMessageTypes);

                if (newConfiguration.TransportSettings != null)
                {
                    if (newConfiguration.TransportSettings.ListenPort != portNumber)
                    {
                        log.InfoFormat("Changing Socket Transport Port to {0}",
                                       newConfiguration.TransportSettings.ListenPort);
                        portNumber = newConfiguration.TransportSettings.ListenPort;
                        SocketServerAdapter.ChangePort(portNumber);
                    }
                    if (newConfiguration.TransportSettings.HttpListenPort != httpPortNumber)
                    {
                        if (httpPortNumber < 1 && newConfiguration.TransportSettings.HttpListenPort > 0)                         //there was no http server and now we want one
                        {
                            httpPortNumber = newConfiguration.TransportSettings.HttpListenPort;
                            StartHttpServer();
                        }
                        else if (newConfiguration.TransportSettings.HttpListenPort < 1 && httpPortNumber > 0)                         //shut off a running server
                        {
                            httpPortNumber = newConfiguration.TransportSettings.HttpListenPort;
                            StopHttpServer();
                        }
                        else                         //just change the port on an existing server
                        {
                            log.InfoFormat("Changing Http Transport Port to {0}",
                                           newConfiguration.TransportSettings.HttpListenPort);
                            httpPortNumber = newConfiguration.TransportSettings.HttpListenPort;
                            _httpServer.ChangePort(httpPortNumber);
                        }
                    }
                }

                if (newConfiguration.NumberOfThreads != configuration.NumberOfThreads)
                {
                    if (log.IsInfoEnabled)
                    {
                        log.InfoFormat("Changing number of relay node threads from {0} to {1}",
                                       configuration.NumberOfThreads, newConfiguration.NumberOfThreads);
                    }
                    try
                    {
                        Dispatcher   oldInDispatcher = inDispatcher;
                        Dispatcher   newInDispatcher;
                        const string inThreadsName = "DataRelayNode";
                        if (newConfiguration.NumberOfThreads > 0)
                        {
                            newInDispatcher = new Dispatcher(newConfiguration.NumberOfThreads, ThreadPriority.Normal, true, inThreadsName);
                        }
                        else
                        {
                            newInDispatcher = new Dispatcher()
                            {
                                Name = inThreadsName
                            };
                        }

                        DispatcherQueue newInQueue = new DispatcherQueue("DataRelayDispatcherQueue", newInDispatcher, TaskExecutionPolicy.ConstrainQueueDepthThrottleExecution, newConfiguration.MaximumMessageQueueDepth);

                        Interlocked.Exchange(ref inMessagePort, new Port <RelayMessage>());
                        Interlocked.Exchange(ref inMessageWithContextPort, new Port <RelayMessageWithContext>());
                        Interlocked.Exchange(ref inMessagesPort, new Port <IList <RelayMessage> >());

                        Arbiter.Activate(newInQueue,
                                         Arbiter.Receive <RelayMessage>(true, inMessagePort, HandleInMessage));
                        Arbiter.Activate(newInQueue,
                                         Arbiter.Receive <RelayMessageWithContext>(true, inMessageWithContextPort, HandleInMessage));
                        Arbiter.Activate(newInQueue,
                                         Arbiter.Receive <IList <RelayMessage> >(true, inMessagesPort, HandleInMessages));

                        inMessageQueue = newInQueue;
                        inDispatcher   = newInDispatcher;
                        oldInDispatcher.Dispose();
                    }
                    catch (Exception e)
                    {
                        if (log.IsErrorEnabled)
                        {
                            log.ErrorFormat("Error changing number of relay node threads: {0}", e);
                        }
                    }
                }
                else
                {
                    //not rebuilding the queue, but reset its max queue depth anyway
                    inMessageQueue.MaximumQueueDepth = newConfiguration.MaximumMessageQueueDepth;
                }

                SetupOutMessagesOnRelayThreads(newConfiguration);

                queuedTaskThreshold = (int)Math.Floor(0.9 * newConfiguration.MaximumMessageQueueDepth);
                configuration       = newConfiguration;
                if (log.IsInfoEnabled)
                {
                    log.Info("Done Reloading configs.");
                }
            }
            else
            {
                if (log.IsErrorEnabled)
                {
                    log.Error("Attempt to reload null config");
                }
            }
        }
コード例 #32
0
        protected override void Start()
        {
            base.Start();
            // Add service specific initialization here.


            int[,] arrayCopy = new int[SIZE, SIZE];
            Random r = new Random();

            for (int i = 0; i < SIZE; ++i)
            {
                for (int j = 0; j < SIZE; ++j)
                {
                    array[i, j]     = r.Next(100);
                    arrayCopy[i, j] = array[i, j];
                }
            }

            System.Diagnostics.Stopwatch sp = new System.Diagnostics.Stopwatch();

            sp.Start();

            for (int k = 0; k < SIZE; ++k)
            {
                for (int i = 0; i < SIZE; ++i)
                {
                    for (int j = i; j < SIZE; ++j)
                    {
                        if (arrayCopy[k, i] > arrayCopy[k, j])
                        {
                            int a = arrayCopy[k, i];
                            arrayCopy[k, i] = arrayCopy[k, j];
                            arrayCopy[k, j] = a;
                        }
                    }
                }
            }

            sp.Stop();
            string planeTime = sp.ElapsedMilliseconds.ToString();

            int nc = 4;

            InputData[] data = new InputData[SIZE];

            for (int i = 0; i < SIZE; ++i)
            {
                data[i]     = new InputData();
                data[i].row = new int[SIZE];

                for (int j = 0; j < SIZE; ++j)
                {
                    data[i].row[j] = array[i, j];
                }
            }

            Dispatcher      d  = new Dispatcher(nc, "Test Pool");
            DispatcherQueue dq = new DispatcherQueue("Test Queue", d);

            Port <int> port = new Port <int>();

            for (int i = 0; i < SIZE; i++)
            {
                Arbiter.Activate(dq, new Task <InputData, Port <int> >(data[i], port, Sort));
            }

            Arbiter.Activate(Environment.TaskQueue, Arbiter.MultipleItemReceive(true, port, SIZE, delegate(int[] array)
            {
                Console.WriteLine("Вычисления завершены");
                Console.WriteLine("Parallel sorting time: {0}", fullParallelTime.ToString());
                Console.WriteLine("Linear sorting time: {0}ms", planeTime);
            }));
        }
コード例 #33
0
        private void SetupOutMessagesOnRelayThreads(RelayNodeConfig newConfiguration)
        {
            //if it was off and is now on, or if it was on and the number of threads changed
            bool setupNewOutMessages = (newConfiguration.OutMessagesOnRelayThreads && configuration.OutMessagesOnRelayThreads == false) ||
                                       (configuration.OutMessagesOnRelayThreads && newConfiguration.OutMessagesOnRelayThreads &&
                                        newConfiguration.NumberOfOutMessageThreads != configuration.NumberOfOutMessageThreads);

            Dispatcher      oldOutDispatcher   = outDispatcher;
            DispatcherQueue oldOutMessageQueue = outMessageQueue;

            if (setupNewOutMessages)
            {
                try
                {
                    const string outThreadsName = "DataRelayNodeOUT";

                    outMessagePort  = new Port <RelayMessageAsyncResult>();                   //atomic
                    outMessagesPort = new Port <RelayMessageListAsyncResult>();               //atomic

                    if (newConfiguration.NumberOfOutMessageThreads > 0)
                    {
                        outDispatcher = new Dispatcher(newConfiguration.NumberOfOutMessageThreads, ThreadPriority.Normal, true, outThreadsName);
                    }
                    else
                    {
                        outDispatcher = new Dispatcher {
                            Name = outThreadsName
                        };
                    }

                    outMessageQueue = new DispatcherQueue("DataRelayDispatcherQueueOUT", outDispatcher, TaskExecutionPolicy.ConstrainQueueDepthThrottleExecution, newConfiguration.MaximumOutMessageQueueDepth);

                    Arbiter.Activate(outMessageQueue,
                                     Arbiter.ReceiveWithIterator(true, outMessagePort, HandleOutMessage));
                    Arbiter.Activate(outMessageQueue,
                                     Arbiter.ReceiveWithIterator(true, outMessagesPort, HandleOutMessages));
                }
                catch (Exception e)
                {
                    if (log.IsErrorEnabled)
                    {
                        log.ErrorFormat("Error setting up Out Message Threads on RelayNode: {0}", e);
                    }
                    throw;
                }
            }

            if (newConfiguration.OutMessagesOnRelayThreads == false)
            {
                outMessagePort  = null;
                outMessagesPort = null;
                if (oldOutDispatcher != null)
                {
                    oldOutDispatcher.Dispose();
                }
                if (oldOutMessageQueue != null)
                {
                    oldOutMessageQueue.Dispose();
                }
            }
        }
コード例 #34
0
ファイル: Errors.cs プロジェクト: kaagati/spectre
 public static void ThrowInvalidCrossThreadCall(DispatcherQueue correctQueue)
 {
     var message = string.Format("Method called on invalid thread, please invoke into the {0} queue.",
                                 correctQueue);
     throw new InvalidOperationException(message);
 }
コード例 #35
0
        /// <summary>
        /// Initializes the <see cref="RelayNode"/> with the given <see cref="ComponentRunState"/>s,
        /// must be called before calling <see cref="Start"/>
        /// </summary>
        /// <param name="componentRunStates"></param>
        public void Initialize(ComponentRunState[] componentRunStates)
        {
            try
            {
                if (log.IsInfoEnabled)
                {
                    if (componentRunStates == null)
                    {
                        log.Info("Initializing Relay Node.");
                    }
                    else
                    {
                        log.Info("Initialzing Relay Node with Component Run States.");
                    }
                }

                EnvironmentManager.EnvironmentChanged += EnvironmentChangedHandler;

                GetConfig();

                if (configuration == null)
                {
                    throw new ConfigurationErrorsException("config failed to load, is null");
                }

                SetClusterAddresses(configuration);

                fatalFailureTimeout = configuration.FatalShutdownTimeout < 0
                                        ? TimeSpan.FromMinutes(5)
                                        : TimeSpan.FromSeconds(configuration.FatalShutdownTimeout);

                components = new RelayComponents(configuration);

                if (configuration != null)
                {
                    messageTracer           = new MessageTracer(configuration.TypeSettings.MaxTypeId, configuration.TraceSettings);
                    messageTracer.Activated = configuration.OutputTraceInfo;

                    const string inThreadsName = "DataRelayNode";
                    if (configuration.NumberOfThreads > 0)
                    {
                        inDispatcher = new Dispatcher(configuration.NumberOfThreads, ThreadPriority.Normal, true, inThreadsName);
                    }
                    else
                    {
                        inDispatcher = new Dispatcher()
                        {
                            Name = inThreadsName
                        };
                    }

                    const string outThreadsName = "DataRelayNodeOUT";
                    if (configuration.OutMessagesOnRelayThreads)
                    {
                        if (configuration.NumberOfOutMessageThreads > 0)
                        {
                            outDispatcher = new Dispatcher(configuration.NumberOfOutMessageThreads, ThreadPriority.Normal, true, outThreadsName);
                        }
                        else
                        {
                            outDispatcher = new Dispatcher {
                                Name = outThreadsName
                            };
                        }

                        outMessagePort  = new Port <RelayMessageAsyncResult>();
                        outMessagesPort = new Port <RelayMessageListAsyncResult>();

                        outMessageQueue = new DispatcherQueue("DataRelayDispatcherQueueOUT", outDispatcher, TaskExecutionPolicy.ConstrainQueueDepthThrottleExecution, configuration.MaximumOutMessageQueueDepth);
                        Arbiter.Activate(outMessageQueue,
                                         Arbiter.ReceiveWithIterator(true, outMessagePort, HandleOutMessage));
                        Arbiter.Activate(outMessageQueue,
                                         Arbiter.ReceiveWithIterator(true, outMessagesPort, HandleOutMessages));
                    }

                    inMessageQueue = new DispatcherQueue("DataRelayDispatcherQueue", inDispatcher, TaskExecutionPolicy.ConstrainQueueDepthThrottleExecution, configuration.MaximumMessageQueueDepth);

                    queuedTaskThreshold = (int)Math.Floor(0.9 * configuration.MaximumMessageQueueDepth);


                    // setup RelayServicesClient before initalizing components
                    RelayServicesClient.Instance.RelayNodeServices = this;

                    Arbiter.Activate(inMessageQueue,
                                     Arbiter.Receive <RelayMessage>(true, inMessagePort, HandleInMessage));
                    Arbiter.Activate(inMessageQueue,
                                     Arbiter.Receive <RelayMessageWithContext>(true, inMessageWithContextPort, HandleInMessage));
                    Arbiter.Activate(inMessageQueue,
                                     Arbiter.Receive <IList <RelayMessage> >(true, inMessagesPort, HandleInMessages));


                    //by having after the Arbiter.Activate it allows Initialize components to use
                    //IRelayNodeServices that require Message handling
                    components.Initialize(componentRunStates, configuration.IgnoredMessageTypes);

                    queuedMessageCounterTimer = new Timer(CountQueuedMessages, null, 5000, 5000);
                }
            }
            catch (Exception ex)
            {
                if (log.IsErrorEnabled)
                {
                    log.ErrorFormat("Exception initializing relay node: {0}", ex);
                }
                throw;                 //should bring server down
            }
        }