Пример #1
0
        public void Invoke(Windows.UI.Core.DispatchedHandler handler)
        {
            // Validate argument.
            if (handler == null)
            {
                throw new NullReferenceException("handler");
            }

            // Invoke the given handler on the main UI thread now. (This is a block call.)
            System.Windows.Threading.Dispatcher dispatcher = System.Windows.Deployment.Current.Dispatcher;
            if (dispatcher.CheckAccess())
            {
                handler.Invoke();
            }
            else if (sIsDispatcherValid)
            {
                var waitEvent = new System.Threading.AutoResetEvent(false);
                var operation = dispatcher.BeginInvoke(() =>
                {
                    handler.Invoke();
                    waitEvent.Set();
                });
                waitEvent.WaitOne();
            }
        }
Пример #2
0
        private async void _btnReadFile_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                var _totalLinesFile      = File.ReadLines(@"Assets/data.txt").Count();
                var _numLineasProcesadas = 1;
                _btnReadFile.IsEnabled = false; // Deshabilitamos boton

                // https://docs.microsoft.com/en-us/uwp/api/windows.storage.storagefile.getfilefromapplicationuriasync
                StorageFile _file = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///Assets/data.txt"));

                // https://social.msdn.microsoft.com/Forums/sqlserver/en-US/add089a4-a67e-4b98-91af-67d23189d5d4/uwp-how-to-read-a-text-file?forum=wpdevelop
                StreamReader _readFile = new StreamReader(await _file.OpenStreamForReadAsync());

                Windows.UI.Core.DispatchedHandler _actionReadFile = async() =>
                {
                    while (_numLineasProcesadas <= _totalLinesFile)
                    {
                        _txtPorcentaje.Text = Math.Round((_numLineasProcesadas * 100.0) / _totalLinesFile).ToString() + " %";
                        _proArchivo.Value   = (_numLineasProcesadas * 100) / _totalLinesFile;
                        _numLineasProcesadas++;
                        await Task.Delay(20);
                    }
                    _btnReadFile.IsEnabled = true; // Habilitamos Boton
                };
                await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, _actionReadFile);
            } catch (IOException ex) { }
        }
Пример #3
0
        private async Task createNewViewIfNeeded(Windows.UI.Core.DispatchedHandler initAction)
        {
            if (Window.Current.Content == null)
            {
                await Window.Current.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, initAction);

                return;
            }
            var newViewId = 0;
            var newView   = Windows.ApplicationModel.Core.CoreApplication.CreateNewView();
            var init      = newView.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, initAction);
            await newView.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
            {
                var newAppView           = ApplicationView.GetForCurrentView();
                newViewId                = newAppView.Id;
                newAppView.Consolidated += (sender, e) =>
                {
                    ViewModel.ViewModelLocator.ClearForView(newViewId);
                    Window window = null;
                    if (WindowDictionary.TryRemove(newViewId, out window))
                    {
                        window.Content = null;
                    }
                };
            });

            await ApplicationViewSwitcher.TryShowAsStandaloneAsync(newViewId);

            await init;
        }
Пример #4
0
        async private void GPS_PositionChanged(Geolocator sender, PositionChangedEventArgs args)
        {
            //Geoposition pos = args.Position;

            Geolocator  geolocator = new Geolocator();
            Geoposition pos        = await geolocator.GetGeopositionAsync();

            Geopoint myLocation = pos.Coordinate.Point;

            BasicGeoposition cityPosition = new BasicGeoposition()
            {
                Latitude = 40.390, Longitude = -3.628
            };
            Geopoint cityCenter = new Geopoint(cityPosition);

            Windows.UI.Core.DispatchedHandler Lectura_Posicion = () =>
            {
                MapIcon myPOI = new MapIcon
                {
                    Location = cityCenter,
                    NormalizedAnchorPoint = new Point(0.5, 1.0),
                    Title  = "Campus Sur-UPM",
                    ZIndex = 0,
                    Image  = RandomAccessStreamReference.CreateFromUri(new Uri("ms-appx:///Assets/ubicacion.png"))
                };
                mcMapa.MapElements.Add(myPOI);
                mcMapa.Center           = cityCenter;
                mcMapa.ZoomLevel        = 14;
                mcMapa.LandmarksVisible = true;
            };
            await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, Lectura_Posicion);
        }
Пример #5
0
        private static async void Setup(Windows.UI.Xaml.Controls.Flyout m)
        {
            if (Windows.ApplicationModel.DesignMode.DesignModeEnabled)
            {
                return;
            }
            var s = GetItemsSource(m);

            if (s == null)
            {
                return;
            }
            var t = GetItemTemplate(m);

            if (t == null)
            {
                return;
            }
            var c = new Windows.UI.Xaml.Controls.ItemsControl
            {
                ItemsSource  = s,
                ItemTemplate = t,
            };
            var n = Windows.UI.Core.CoreDispatcherPriority.Normal;

            Windows.UI.Core.DispatchedHandler h = () => m.Content = c;
            await m.Dispatcher.RunAsync(n, h);
        }
Пример #6
0
        public async static void NavigateOnUI(string viewName, object parameter = null)
        {
            Windows.UI.Core.DispatchedHandler invokedHandler = new Windows.UI.Core.DispatchedHandler(() =>
            {
                LoggingService.LogInformation("navigating to " + viewName, "NavigationService.NavigateOnUI");

                Navigate(viewName, parameter);
            });

            await _mainFrame.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, invokedHandler);
        }
Пример #7
0
 public static async Task EnsureOnAsync(Windows.UI.Core.DispatchedHandler callback)
 {
     if (App.Dispatcher.HasThreadAccess)
     {
         callback.Invoke();
     }
     else
     {
         await App.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, callback);
     }
 }
Пример #8
0
 /// <summary>
 /// Allows updating a view model property from a non-UI thread. An example would be running
 /// a task in a thread-pool thread that downloads data the view model needs. Once downloaded
 /// the UI property needs to be updated; however, you cannot access UI elements from a non UI
 /// thread so you marshal it over using this function which calls the Window Dispatcher to run
 /// the given task.
 ///
 /// Use example:
 /// InvokeOnUIThread(() => { DelayedAchievementCount = result; });
 ///
 /// </summary>
 /// <param name="task">
 /// The task to update the desired property
 /// </param>
 protected void InvokeOnUIThread(Windows.UI.Core.DispatchedHandler task)
 {
     if (_syncContext != null && _syncContext != SynchronizationContext.Current)
     {
         _syncContext.Post(delegate { task.Invoke(); }, null);
     }
     else
     {
         task.Invoke();
     }
 }
Пример #9
0
 private void RunOnMainThread(Windows.UI.Core.DispatchedHandler handler)
 {
     if (Dispatcher.HasThreadAccess)
     {
         handler.Invoke();
     }
     else
     {
         // Note: use a discard "_" to silence CS4014 warning
         _ = Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, handler);
     }
 }
Пример #10
0
        public static void NavigateOnUI(eViews viewName, object parameter = null)
        {
            Windows.UI.Core.DispatchedHandler invokedHandler = new Windows.UI.Core.DispatchedHandler(() =>
            {
                // LoggingService.LogInformation("navigating to " + viewName, "NavigationService.NavigateOnUI");

                Current.Navigate(viewName, parameter);
            });

            //if (_mainFrame != null) await _mainFrame.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, invokedHandler);
            //else if (_contentFrame != null) await _contentFrame.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, invokedHandler);
        }
Пример #11
0
        public static Task RunOnMainThread(Windows.UI.Core.DispatchedHandler handler)
        {
            var dispatcher = Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher;

            if (dispatcher.HasThreadAccess)
            {
                handler.Invoke();
                return(Task.CompletedTask);
            }
            else
            {
                return(dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, handler).AsTask());
            }
        }
Пример #12
0
        public void InvokeAsync(Windows.UI.Core.DispatchedHandler handler)
        {
            // Validate argument.
            if (handler == null)
            {
                throw new NullReferenceException("handler");
            }

            // Do not continue if dispatchers can no longer be used, which happen while the application is exiting.
            if (sIsDispatcherValid == false)
            {
                return;
            }

            // Queue the given handler to be invoked on the main UI thread later.
            System.Windows.Deployment.Current.Dispatcher.BeginInvoke(handler, null);
        }
Пример #13
0
        public static async Task MarshallToUiThread(Windows.UI.Core.DispatchedHandler fn)
        {
            if (uiDispatcher == null)
            {
                uiDispatcher = Windows.UI.Core.CoreWindow.GetForCurrentThread()?.Dispatcher;
                if (uiDispatcher == null)
                {
                    System.Diagnostics.Debug.WriteLine("Could not get ui dispatcher.");
                    return;
                }
            }

            await uiDispatcher
            .RunAsync(
                Windows.UI.Core.CoreDispatcherPriority.Normal,
                fn);
        }
Пример #14
0
 public static async Task OnMainThread(Windows.UI.Core.DispatchedHandler action)
 {
     var mainView = Windows.ApplicationModel.Core.CoreApplication.MainView;
     var normal   = Windows.UI.Core.CoreDispatcherPriority.Normal;
     await mainView.CoreWindow.Dispatcher.RunAsync(normal, action);
 }
Пример #15
0
 public static async void EnsureOn(Windows.UI.Core.DispatchedHandler callback)
 {
     await EnsureOnAsync(callback);
 }
Пример #16
0
        private async void mostrarRutaEnMapa(double latIni, double longIni, double latFin, double longFin, Color color)
        {
            BasicGeoposition startLocation = new BasicGeoposition()
            {
                Latitude = latIni, Longitude = longIni
            };

            BasicGeoposition endLocation = new BasicGeoposition()
            {
                Latitude = latFin, Longitude = longFin
            };

            MapRouteFinderResult routeResult =
                await MapRouteFinder.GetDrivingRouteAsync(
                    new Geopoint(startLocation),
                    new Geopoint(endLocation),
                    MapRouteOptimization.Time,
                    MapRouteRestrictions.None);

            if (routeResult.Status == MapRouteFinderStatus.Success)
            {
                MapRouteView viewOfRoute = new MapRouteView(routeResult.Route);
                viewOfRoute.RouteColor   = color;// Colors.Orange;
                viewOfRoute.OutlineColor = Colors.Black;

                mcMapa.Routes.Add(viewOfRoute);


                await mcMapa.TrySetViewBoundsAsync(
                    routeResult.Route.BoundingBox,
                    null,
                    Windows.UI.Xaml.Controls.Maps.MapAnimationKind.None);

                BasicGeoposition cityPosition = new BasicGeoposition()
                {
                    Latitude = latIni, Longitude = longIni
                };
                Geopoint cityCenter = new Geopoint(cityPosition);

                Windows.UI.Core.DispatchedHandler Lectura_PosicionIni = () =>
                {
                    MapIcon myPOI = new MapIcon
                    {
                        Location = cityCenter,
                        NormalizedAnchorPoint = new Point(0.5, 1.0),
                        Title  = txtOrigen.Text,
                        ZIndex = 0,
                        Image  = RandomAccessStreamReference.CreateFromUri(new Uri("ms-appx:///Assets/ubicacion-start.png"))
                    };
                    mcMapa.MapElements.Add(myPOI);
                };
                await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, Lectura_PosicionIni);

                BasicGeoposition cityPositionEnd = new BasicGeoposition()
                {
                    Latitude = latFin, Longitude = longFin
                };
                Geopoint cityCenterEnd = new Geopoint(cityPositionEnd);

                Windows.UI.Core.DispatchedHandler Lectura_PosicionEnd = () =>
                {
                    MapIcon myPOI = new MapIcon
                    {
                        Location = cityCenterEnd,
                        NormalizedAnchorPoint = new Point(0.5, 1.0),
                        Title  = txtDestino.Text,
                        ZIndex = 0,
                        Image  = RandomAccessStreamReference.CreateFromUri(new Uri("ms-appx:///Assets/ubicacion-end.png"))
                    };
                    mcMapa.MapElements.Add(myPOI);
                };
                await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, Lectura_PosicionEnd);
            }
        }
Пример #17
0
        private async void Button_Click(object sender, RoutedEventArgs e)
        {
            Geopoint lastPoint = new Geopoint(new BasicGeoposition()), currentPoint;

            Windows.UI.Core.DispatchedHandler actualizarTextBox = async() =>
            {
                HttpClient          client = new HttpClient();
                HttpResponseMessage stream = await client.GetAsync(urlInicial + lugarIncialTextBox.Text + urlMedio + lugarFinalTextBox.Text + urlFinal);

                //Si ha obtenido una ruta como respuesta, escribe en el mapa
                if (stream.IsSuccessStatusCode)
                {
                    String str = await stream.Content.ReadAsStringAsync();

                    JsonValue jsonValue = JsonValue.Parse(str);
                    arrayRuta = jsonValue.GetObject().GetNamedArray("resourceSets").GetObjectAt(0).GetNamedArray("resources").GetObjectAt(0).GetNamedArray("routeLegs").GetObjectAt(0).GetNamedArray("itineraryItems");

                    //Bucle que dibuja cada punto de la ruta y la ruta entre el punto actual y el anterior en el mapa
                    var first = arrayRuta.First();
                    foreach (var puntoRuta in arrayRuta)
                    {
                        PuntoBing puntoBing = obtenerPunto(puntoRuta.GetObject());

                        currentPoint = geopositionPoint(puntoBing.Latitude, puntoBing.Longitude);
                        string nombres = "";
                        foreach (string nombre in puntoBing.Nombre)
                        {
                            nombres = nombres + Environment.NewLine + nombre;
                        }
                        mapIconRuta = new MapIcon
                        {
                            Location = currentPoint,
                            Title    = nombres
                        };
                        mapView.MapElements.Add(mapIconRuta);

                        puntos.Add(puntoBing);
                        escribePunto(puntoBing);

                        //Si el punto actual es el último, pasa a ser el actual en el código

                        if (!puntoRuta.Equals(first))
                        {
                            // Obtiene la ruta entre el punto anterior y el actual.
                            MapRouteFinderResult routeResult =
                                await MapRouteFinder.GetDrivingRouteAsync(
                                    startPoint : lastPoint,
                                    endPoint : currentPoint,
                                    optimization : MapRouteOptimization.Time,
                                    restrictions : MapRouteRestrictions.None);

                            if (routeResult.Status == MapRouteFinderStatus.Success)
                            {
                                // Usa la ruta para inicializar MapRouteView.
                                MapRouteView viewOfRoute = new MapRouteView(routeResult.Route);
                                viewOfRoute.RouteColor   = Colors.Yellow;
                                viewOfRoute.OutlineColor = Colors.Black;

                                // Añade el nuevo MapRouteView al conjunto de rutas
                                // de MapControl.
                                mapView.Routes.Add(viewOfRoute);

                                //El punto actual se convierte en el anterior
                                lastPoint = currentPoint;
                            }
                        }
                        else
                        {
                            lastPoint = currentPoint;
                        }
                    }
                }
                else
                {
                    rutaTextBox.Text = "Mal";
                }
            };

            await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, actualizarTextBox);
        }
Пример #18
0
 public static async Task RunOnUIThreadAsync(Windows.UI.Core.DispatchedHandler handler)
 {
     await Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, handler);
 }
Пример #19
0
        public async static void NavigateOnUI(string viewName, object parameter = null)
        {
            Windows.UI.Core.DispatchedHandler invokedHandler = new Windows.UI.Core.DispatchedHandler(() =>
            {
                LoggingService.LogInformation("navigating to " + viewName, "NavigationService.NavigateOnUI");

                Navigate(viewName, parameter);
            });

            await _mainFrame.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, invokedHandler);
        }
Пример #20
0
 public static async System.Threading.Tasks.Task CallOnUiThreadAsync(Windows.UI.Core.DispatchedHandler handler) =>
 await Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, handler);
 private IAsyncAction RunOnUi(Windows.UI.Core.DispatchedHandler action)
 {
     return(Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, action));
 }
Пример #22
0
 public static IAsyncAction ExecuteOnUIThread(Windows.UI.Core.DispatchedHandler action)
 {
     return(Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, action));
 }
Пример #23
0
 private static async void EnsureOnUI(Windows.UI.Core.DispatchedHandler callback)
 {
     await EnsureOnUIAsync(callback);
 }