public Wait Commit(bool sameThread = false) { Continue = true; Action act = () => { Thread.Sleep(Sleep); lock (LockObj) { if (!Continue) { return; } foreach (var f in Funcs) { f(); } } }; if (sameThread) { act(); } else { new Thread(() => UIThread.InvokeOnMainThread(() => act())).Start(); } return(this); }
public static void SetImageFromStream(Task <Stream> taskToAwait, UIImageView imageView, NSObject context, int newWidth, int newHeight) { taskToAwait.ContinueWith(t => { if (!t.IsFaulted && t.Result != null) { var data = NSData.FromStream(t.Result); context.InvokeOnMainThread(() => { var image = UIImage.LoadFromData(data); if (image != null && imageView != null) { UIGraphics.BeginImageContext(new SizeF(newWidth, newHeight)); image.Draw(new RectangleF(0, 0, newWidth, newHeight)); image = UIGraphics.GetImageFromCurrentImageContext(); UIGraphics.EndImageContext(); imageView.Image = image; } }); } else { Console.WriteLine(t.Exception.ToString()); } }); }
void LoadAssetsWorkerThread () { #if MACOS || IOS // Create an Autorelease Pool or we will leak objects. using (var pool = new NSAutoreleasePool()) { #else #endif // Make sure we invoke this on the Main Thread or OpenGL will throw an error #if MACOS MonoMac.AppKit.NSApplication.SharedApplication.BeginInvokeOnMainThread (delegate { #endif #if IOS var invokeOnMainThredObj = new NSObject(); invokeOnMainThredObj.InvokeOnMainThread(delegate { #endif gameplayScreen.LoadAssets (); #if MACOS || IOS }); } #endif }
public static async Task <T1> InvokeOnUIThread <T1>(Func <Task <T1> > function) { if (!NSThread.IsMain) { var signal = new ManualResetEventSlim(); var result = default(T1); Exception exception = null; var obj = new NSObject(); obj.InvokeOnMainThread(async() => { try { result = await function(); } catch (Exception error) { exception = error; } finally { signal.Set(); } }); if (exception != null) { throw new Exception("An exception occured whilst executing function in UI thread.", exception); } await Task.Run(() => signal.Wait()); return(result); } return(await function()); }
public void Invoke(Code code) { using (var a = new NSAutoreleasePool()) { obj.InvokeOnMainThread(() => code()); } }
static void ShowBadLines(Stream stream, Dictionary <long, Tuple <string, string> > lineErrors) { #if __MACOS__ if (!NSThread.IsMain) { Invoker.InvokeOnMainThread(() => ShowBadLines(stream, lineErrors)); return; } #endif try { int result = UIHelpers.ShowYesNo("Would you like to view the line error report?"); if (result == UIHelpers.Yes) { string tempFile = CreateTempFile(); if (!string.IsNullOrEmpty(tempFile)) { tempFile = tempFile.Substring(0, tempFile.Length - 3) + "html"; stream.Position = 0; FileStream fileStream = new FileStream(tempFile, FileMode.Create, FileAccess.Write); using (StreamWriter writer = new StreamWriter(fileStream)) { using (StreamReader reader = new StreamReader(stream)) { writer.WriteLine("<html><head><Title>Gedcom File</Title></head><body>"); writer.WriteLine("<h4>Line Errors</h4>"); writer.WriteLine("<table border='1'><tr><th>Line Number</th><th>Line Contents</th><th>Error Description</th></tr>"); foreach (KeyValuePair <long, Tuple <string, string> > kvp in lineErrors) { writer.WriteLine($"<tr><td><a href='#{kvp.Key}'>{kvp.Key}</a></td><td>{kvp.Value.Item1}</td><td>{kvp.Value.Item2}</td></tr>"); } writer.WriteLine("</table><h4>GEDCOM Contents</h4><table border='1'><tr><th>Line Number</th><th>Line Contents</th></tr>"); string line = reader.ReadLine(); long lineNr = 1; while (line != null) { if (lineErrors.ContainsKey(lineNr)) { writer.WriteLine($"<tr id='{lineNr}'><td>{lineNr++}</td><td>{line}</td></tr>"); } else { writer.WriteLine($"<tr><td>{lineNr++}</td><td>{line}</td></tr>"); } line = reader.ReadLine(); } writer.Write("</table></body></html>"); } } SpecialMethods.VisitWebsite(tempFile); } } } catch (Exception e) { Console.WriteLine($"Error: {e.Message}"); } }
public static void ShowMessage(string title, string message, MessageBoxButton buttons, Action positiveCallback, Action negativeCallback) { UIAlertView alert = BuildAlert(title, message, buttons); alert.Clicked += (sender, buttonArgs) => { if (buttonArgs.ButtonIndex == 0) { positiveCallback(); } else { negativeCallback(); } }; nsObject.InvokeOnMainThread(alert.Show); }
public static Task <string> Input(string title, string message, string button = "Ok", UIKeyboardType type = UIKeyboardType.ASCIICapable, string defValue = "") { var tcs = new TaskCompletionSource <string>(); var alert = new UIAlertView(title, message, null, button, null); alert.AlertViewStyle = UIAlertViewStyle.PlainTextInput; var txt = alert.GetTextField(0); txt.Text = defValue; txt.KeyboardType = type; alert.Clicked += (sender, e) => tcs.SetResult(alert.GetTextField(0).Text); UIThread.InvokeOnMainThread(alert.Show); return(tcs.Task); }
public Task <GeoDirection> GetDirectionsAsync(double originLat, double originLng, double destLat, double destLng, DateTime?date) { var tcs = new TaskCompletionSource <GeoDirection>(); var result = new GeoDirection(); var o = new NSObject(); o.InvokeOnMainThread(() => { try { var origin = new CLLocationCoordinate2D(originLat, originLng); var destination = new CLLocationCoordinate2D(destLat, destLng); var emptyDict = new NSDictionary(); var req = new MKDirectionsRequest { Source = new MKMapItem(new MKPlacemark(origin, emptyDict)), Destination = new MKMapItem(new MKPlacemark(destination, emptyDict)), TransportType = MKDirectionsTransportType.Automobile, }; if (date.HasValue) { req.DepartureDate = DateTimeToNSDate(date.Value); } var dir = new MKDirections(req); dir.CalculateDirections((response, error) => { if (error == null) { var route = response.Routes [0]; result.Distance = Convert.ToInt32(route.Distance); result.Duration = Convert.ToInt32(route.ExpectedTravelTime); } else { _logger.LogMessage("Error with CalculateDirections"); _logger.LogMessage("Error Code: " + error.Code); _logger.LogMessage("Description: " + error.LocalizedDescription); } tcs.TrySetResult(result); }); } catch (Exception ex) { _logger.LogMessage("Exception in AppleDirectionProvider"); _logger.LogError(ex); tcs.TrySetResult(result); } }); return(tcs.Task); }
public void InvokeOnMainThread(Action action) { if (NSThread.Current.IsMainThread) { action(); } else { _invoker.InvokeOnMainThread(() => action()); } }
public static Task ContinueOnUIThread <T>(this Task <T> task, Action <Task <T> > action, TaskContinuationOptions tco) { return(task.ContinueWith(t => UIThread.InvokeOnMainThread(() => { try { action(t); } catch (Exception ex) { if (LogFunction == null) { Alert.Show("Error", ex.ToString()); } else { LogFunction(ex); } #if DEBUG Alert.Show("Error", ex.ToString()); #endif } }), tco)); }
public static T CreateOnMainThread <T>(this NSObject nsObject) where T : new() { if (NSThread.Current.IsMainThread) { return(new T()); } T result = default(T); nsObject.InvokeOnMainThread(() => new T()); return(result); }
public void MarshalOnUIThread(Action a) { _obj.InvokeOnMainThread(() => { try { a(); } catch (Exception e) { System.Diagnostics.Debug.WriteLine("Attempt to marshal on main thread ended in exception: " + e.Message); System.Diagnostics.Debugger.Break(); } }); }
static void TryLoadController(MXContainer container, IMXView fromView, IMXController controller, Dictionary <string, object> parameters) { try { NSObject nso = new NSObject(); nso.InvokeOnMainThread(() => { container.LoadController(fromView, controller, parameters); }); } catch (Exception ex) { container.OnControllerLoadFailed(controller, ex); } }
public static void SetImageFromStream(Task <Stream> taskToAwait, UIImageView imageView, NSObject context) { taskToAwait.ContinueWith(t => { if (!t.IsFaulted && t.Result != null) { var data = NSData.FromStream(t.Result); context.InvokeOnMainThread(() => { var image = UIImage.LoadFromData(data); imageView.Image = image; }); } else { Console.WriteLine(t.Exception.ToString()); } }); }
private void OnTimedEvent(object sender, System.Timers.ElapsedEventArgs e) { //http://docs.xamarin.com/guides/ios/application_fundamentals/threading/ //http://msdn.microsoft.com/en-us/library/8ysw4sby(v=vs.110).aspx DateTime elapsedTime = new DateTime(); elapsedTime = DateTime.Now; NSObject cobj = new NSObject(); cobj.InvokeOnMainThread(delegate { lblTimer.Text = elapsedTime.Subtract(startTime).ToString(@"hh\:mm\:ss"); }); }
public void SetGetClipboard_RoundtripCase_ResultIsCorrect() { var invoker = new NSObject(); invoker.InvokeOnMainThread(() => { // Arrange var text = "test string"; // Act CrossClipboard.Current.SetText(text); var actual = CrossClipboard.Current.GetTextAsync().Result; // Assert Assert.AreEqual(text, actual); }); }
private Task <MKPlacemark[]> SearchAsync(string query, double?lat, double?lng, double radiusInMeters) { var tcs = new TaskCompletionSource <MKPlacemark[]>(); var result = new MKPlacemark[0]; var o = new NSObject(); o.InvokeOnMainThread(async() => { try { var searchRequest = new MKLocalSearchRequest { NaturalLanguageQuery = query }; if (lat.HasValue && lng.HasValue && lat.Value != 0 && lng.Value != 0) { // You can use this parameter to narrow the list of search results to those inside or close to the specified region. // Specifying a region does not guarantee that the results will all be inside the region. It is merely a hint to the search engine. var region = MKCoordinateRegion.FromDistance(new CLLocationCoordinate2D(lat.Value, lng.Value), radiusInMeters * 2, radiusInMeters * 2); searchRequest.Region = region; } var search = new MKLocalSearch(searchRequest); var searchResult = await search.StartAsync(); result = searchResult.MapItems.Select(x => x.Placemark).ToArray(); } catch (Exception ex) { Console.WriteLine(ex.Message); } finally { tcs.TrySetResult(result); } }); return(tcs.Task); }
public static void ShowSetupGameScreen(FriendViewModel friendModel, UINavigationController nav, NSObject context) { var viewModel = new GameSetupViewModel(AppDelegate.Repository); viewModel.Opponent = friendModel; BTProgressHUD.Show("Loading", -1, ProgressHUD.MaskType.Black); viewModel.InitializeAsync().ContinueWith(t => { context.InvokeOnMainThread(() => { BTProgressHUD.Dismiss(); if (!t.IsFaulted && t.Result) { var controller = new GameSetupDialogViewController(viewModel); nav.PushViewController(controller, true); } else { // TODO error } }); }); }
/// <summary> /// Invokes provided action on main UI thread. /// </summary> /// <param name="object">Source object.</param> /// <param name="action">Action to invoke.</param> public static void InvokeOnMainThreadIfNeeded(this NSObject @object, Action action) { if (@object == null) { throw new ArgumentNullException(nameof(@object)); } if (action == null) { throw new ArgumentNullException(nameof(action)); } if (NSThread.IsMain) { action.Invoke(); } else { @object.InvokeOnMainThread(action); } }
public static Task <int> Show(UIView view, string title, string cancel, string destroy, string[] options) { var tcs = new TaskCompletionSource <int>(); var sheet = new UIActionSheet(title, null, cancel, destroy, options); sheet.Clicked += (sender, e) => { if (e.ButtonIndex == sheet.CancelButtonIndex) { tcs.SetResult(-1); } else if (e.ButtonIndex == sheet.DestructiveButtonIndex) { tcs.SetResult(-2); } else { tcs.SetResult(e.ButtonIndex - 1); } }; UIThread.InvokeOnMainThread(() => sheet.ShowInView(view)); return(tcs.Task); }
public void LaunchView(string visualization, string targetdirectory) { invoker.InvokeOnMainThread(() => { try { string filepath = Path.Combine(targetdirectory, visualization); filepath = Path.Combine(filepath, "index.html"); var datavizController = new DataVisualizationViewController(filepath); var navController = new UINavigationController(datavizController); #if __UNIFIED__ UIApplication.SharedApplication.Delegate.GetWindow().RootViewController.PresentViewController(navController, true, new Action(() => Debug.WriteLine("passive view loaded")) ); #else UIApplication.SharedApplication.Delegate.Window.RootViewController.PresentViewController(navController, true, new NSAction(() => Debug.WriteLine("passive view loaded")) ); #endif } catch (Exception ex) { Debug.WriteLine(ex.Message); } }); }
protected void BindCollection <TElement>(CollectionViewModel <TElement> viewModel, Func <TElement, Element> element, bool activateNow = false) { var weakVm = new WeakReference <CollectionViewModel <TElement> >(viewModel); var weakRoot = new WeakReference <RootElement>(Root); Action updateDel = () => { try { IEnumerable <TElement> items = viewModel.Items; var filterFn = viewModel.FilteringFunction; if (filterFn != null) { items = filterFn(items); } var sortFn = viewModel.SortingFunction; if (sortFn != null) { items = sortFn(items); } var groupingFn = viewModel.GroupingFunction; IEnumerable <IGrouping <string, TElement> > groupedItems = null; if (groupingFn != null) { groupedItems = groupingFn(items); } ICollection <Section> newSections; if (groupedItems == null) { newSections = RenderList(items, element, weakVm.Get()?.MoreItems); } else { newSections = RenderGroupedItems(groupedItems, element, weakVm.Get()?.MoreItems); } CreateEmptyHandler(newSections.Sum(s => s.Elements.Count) == 0); weakRoot.Get()?.Reset(newSections); } catch { } }; viewModel.Bind(x => x.GroupingFunction).Subscribe(_ => updateDel()); viewModel.Bind(x => x.FilteringFunction).Subscribe(_ => updateDel()); viewModel.Bind(x => x.SortingFunction).Subscribe(_ => updateDel()); //The CollectionViewModel binds all of the collection events from the observablecollection + more //So just listen to it. viewModel.CollectionChanged += (sender, e) => _dumb.InvokeOnMainThread(updateDel); if (activateNow) { updateDel(); } }
public void Show(string status = null, float progress = -1, MaskType maskType = MaskType.None, double timeoutMs = 1000) { obj.InvokeOnMainThread(() => ShowProgressWorker(progress, status, maskType, timeoutMs: timeoutMs)); }
void save() { using (new NSAutoreleasePool()) { NSError error = new NSError(); selectedImage = Graphics.PrepareForUpload(selectedImage); selectedImage.AsJPEG().Save(Path.Combine(Util.PicDir,Value),NSDataWritingOptions.Atomic,out error); NSObject invoker = new NSObject(); invoker.InvokeOnMainThread(delegate { completed(); }); } }
public void ExecuteOnMainThread(Action action) { var obj = new NSObject(); obj.InvokeOnMainThread(new NSAction(action)); }
public static void Show(string status = null, float progress = -1, MaskType maskType = MaskType.None) { obj.InvokeOnMainThread(() => SharedView.ShowProgressWorker(progress, status, maskType)); }
//public static void SetImageFromNSUrlSession(string imagePath, UIImageView imageView, NSCache imageCache = null) //{ // UIImage imageFromCache = null; // var url = new NSUrl(EnvironmentConstants.getS3Url() + imagePath); // var noCacheStr = "?nocache=" + String.Format("{0:yyyyMMddHHmmssffff}", DateTime.Now); // var fetchUrl = new NSUrl(EnvironmentConstants.getS3Url() + imagePath + noCacheStr); // if (imageCache != null) // { // imageFromCache = (UIImage)imageCache.ObjectForKey(NSString.FromObject(url.AbsoluteString)); // } // if (imageFromCache != null) // { // imageView.Image = imageFromCache; // } // else // { // var task = NSUrlSession.SharedSession.CreateDataTask(fetchUrl, (data, response, error) => // { // try // { // DispatchQueue.MainQueue.DispatchAsync(() => // { // if (response != null && ((NSHttpUrlResponse)response).StatusCode != 403 && error == null) // { // if (imageCache != null) // { // var imageToCache = UIImage.LoadFromData(data); // imageView.Image = imageToCache; // if (imageToCache != null) // { // imageCache.SetObjectforKey(imageToCache, NSString.FromObject(url.AbsoluteString)); // } // } // else // { // imageView.Image = UIImage.LoadFromData(data); // } // } // }); // } // catch (Exception ex) // { // Utils.HandleException(ex); // } // }); // task.Resume(); // } //} public static void SetImageFromNSUrlSession(string imagePath, UIImageView imageView, NSObject controller, PictureType picType) { UIImage placeholder = UIImage.FromBundle("ImagePlaceholder"); try { if (picType.Equals(PictureType.Profile)) { placeholder = UIImage.FromBundle("Profile"); } if (picType.Equals(PictureType.Group)) { placeholder = UIImage.FromBundle("Group"); } imageView.SetImage(new NSUrl(EnvironmentConstants.getS3Url() + imagePath), placeholder, SDWebImageOptions.ProgressiveDownload, //HighPriority progressBlock: (receivedSize, completedSize) => { if (activityIndicator == null) { controller.InvokeOnMainThread(() => { activityIndicator = new UIActivityIndicatorView(UIActivityIndicatorViewStyle.Gray); imageView.AddSubview(activityIndicator); activityIndicator.Center = imageView.Center; activityIndicator.StartAnimating(); }); } }, completedBlock: (image, error, cacheType, finished) => { Console.WriteLine("Image = " + image); Console.WriteLine("Error = " + error); Console.WriteLine("Cache Type = " + cacheType); Console.WriteLine("Finished = " + finished); if (activityIndicator != null) { controller.InvokeOnMainThread(() => { activityIndicator.RemoveFromSuperview(); activityIndicator = null; }); } if (error != null && error.ToString().Contains("1100")) { imageView.SetImage(new NSUrl(EnvironmentConstants.getS3Url() + imagePath), placeholder, SDWebImageOptions.RetryFailed); } if (image != null) { imageView.Image = image; } }); } catch (Exception e) { Console.WriteLine(e.Message); } }
public void Invoke(Action action) { _obj.InvokeOnMainThread(() => action()); }
protected override void Print(string info) { _object.InvokeOnMainThread(() => Console.WriteLine(info)); }
public void BeginInvoke(Action action) { _host.InvokeOnMainThread(action); }
public void LoadImage(UIView imageView, string userID, string picture, bool isLarge = false, bool temp = false) { string subFolder; if (isLarge) { subFolder = Constants.LargeImageSize.ToString(); } else { subFolder = Constants.SmallImageSize.ToString(); } string saveName = userID + "_" + subFolder + "_" + picture; if (Exists(saveName)) { if (imageView is UIImageView) { ((UIImageView)imageView).Image = Load(saveName); } else if (imageView is UIButton) { ((UIButton)imageView).SetBackgroundImage(Load(saveName), UIControlState.Normal); } else if (imageView is MKAnnotationView) { ((MKAnnotationView)imageView).Image = Load(saveName); } } else { if (imageView is UIImageView) { ((UIImageView)imageView).Image = UIImage.FromBundle(Constants.loadingImage); } else if (imageView is UIButton) { ((UIButton)imageView).SetBackgroundImage(UIImage.FromBundle(Constants.loadingImage), UIControlState.Normal); } else if (imageView is MKAnnotationView) { ((MKAnnotationView)imageView).Image = UIImage.FromBundle(Constants.loadingImage); } string url; if (!temp) { if (Constants.isTestDB) { url = Constants.HostName + Constants.UploadFolderTest + "/" + userID + "/" + subFolder + "/" + picture; } else { url = Constants.HostName + Constants.UploadFolder + "/" + userID + "/" + subFolder + "/" + picture; } } else { if (Constants.isTestDB) { url = Constants.HostName + Constants.TempUploadFolderTest + "/" + userID + "/" + subFolder + "/" + picture; } else { url = Constants.HostName + Constants.TempUploadFolder + "/" + userID + "/" + subFolder + "/" + picture; } } CommonMethods.LoadFromUrlAsyncData(url).ContinueWith((task) => { if (task.Result != null) { Save(saveName, task.Result); context.InvokeOnMainThread(() => { if (imageView is MKAnnotationView) { CoreGraphics.CGRect frame = imageView.Frame; ((MKAnnotationView)imageView).Image = UIImage.LoadFromData(task.Result); //enlarges imageView to 480 dp imageView.Frame = frame; } else if (imageView is UIImageView) { ((UIImageView)imageView).Image = UIImage.LoadFromData(task.Result); } else if (imageView is UIButton) { ((UIButton)imageView).SetBackgroundImage(UIImage.LoadFromData(task.Result), UIControlState.Normal); } else if (imageView is MKAnnotationView) { ((MKAnnotationView)imageView).Image = UIImage.LoadFromData(task.Result); } }); } else { context.InvokeOnMainThread(() => { if (imageView is UIImageView) { if (isLarge) { ((UIImageView)imageView).Image = UIImage.FromBundle(Constants.noImageHD); } else { ((UIImageView)imageView).Image = UIImage.FromBundle(Constants.noImage); } } else if (imageView is UIButton) { ((UIButton)imageView).SetBackgroundImage(UIImage.FromBundle(Constants.noImage), UIControlState.Normal); } else if (imageView is MKAnnotationView) { ((MKAnnotationView)imageView).Image = UIImage.FromBundle(Constants.noImage); } }); } }); } }