private void LoadAsset(AVAsset asset, string[] assetKeysToLoad, DispatchGroup dispatchGroup) { dispatchGroup.Enter(); asset.LoadValuesAsynchronously(assetKeysToLoad, () => { // First test whether the values of each of the keys we need have been successfully loaded. foreach (var key in assetKeysToLoad) { if (asset.StatusOfValue(key, out NSError error) == AVKeyValueStatus.Failed) { Console.WriteLine($"Key value loading failed for key:{key} with error: {error?.LocalizedDescription ?? ""}"); goto bail; } } if (!asset.Composable) { Console.WriteLine("Asset is not composable"); goto bail; } this.clips.Add(asset); // This code assumes that both assets are atleast 5 seconds long. var value = NSValue.FromCMTimeRange(new CMTimeRange { Start = CMTime.FromSeconds(0, 1), Duration = CMTime.FromSeconds(5, 1) }); this.clipTimeRanges.Add(value); bail: dispatchGroup.Leave(); }); }
void loadAsset(AVAsset asset, string[] assetKeysToLoad, DispatchGroup dispatchGroup) { dispatchGroup.Enter(); asset.LoadValuesAsynchronously(assetKeysToLoad, () => { foreach (var key in assetKeysToLoad) { NSError error; if (asset.StatusOfValue(key, out error) == AVKeyValueStatus.Failed) { Console.Error.WriteLine("Key value loading failed for key" + key + " with error: " + error.ToString()); dispatchGroup.Leave(); } } if (!asset.Composable) { Console.Error.WriteLine("Asset is not composable"); dispatchGroup.Leave(); } Clips.Add(asset); ClipTimeRanges.Add(NSValue.FromCMTimeRange(new CMTimeRange() { Start = CMTime.FromSeconds(0, 1), Duration = CMTime.FromSeconds(5, 1) })); dispatchGroup.Leave(); }); }
//Simple Editor void setupEditingAndPlayback() { var path1 = NSBundle.MainBundle.PathForResource("sample_clip1", "m4v"); var path2 = NSBundle.MainBundle.PathForResource("sample_clip2", "mov"); var asset1 = AVAsset.FromUrl(new NSUrl(path1, false)) as AVUrlAsset; var asset2 = AVAsset.FromUrl(new NSUrl(path2, false)) as AVUrlAsset; DispatchGroup dispatchGroup = DispatchGroup.Create(); string[] assetKeys = { "tracks", "duration", "composable" }; loadAsset(asset1, assetKeys, dispatchGroup); loadAsset(asset2, assetKeys, dispatchGroup); // Wait until both assets are loaded dispatchGroup.Wait(DispatchTime.Forever); InvokeOnMainThread(delegate { synchronizeWithEditor(); }); }
public void EnterLeaveTest() { using (var dg = DispatchGroup.Create()) { dg.Enter(); Assert.IsFalse(dg.Wait(new DispatchTime(1000 * 1000 * 1000)), "#1"); dg.Leave(); Assert.IsTrue(dg.Wait(DispatchTime.Forever), "#2"); } }
public void NotifyWithAction() { using (var dg = new DispatchGroup()) { var called = false; var callback = new Action(() => called = true); dg.Notify(DispatchQueue.MainQueue, callback); TestRuntime.RunAsync(DateTime.Now.AddSeconds(5), () => { }, () => called); Assert.IsTrue(called, "Called"); } }
public void WaitTest() { using (var dg = DispatchGroup.Create()) { var dq = DispatchQueue.GetGlobalQueue(DispatchQueuePriority.Default); dg.DispatchAsync(dq, delegate { Console.WriteLine("Inside dispatch"); }); Assert.IsTrue(dg.Wait(DispatchTime.Forever)); dq.Dispose(); } }
public void NotifyWithDispatchBlock() { TestRuntime.AssertSystemVersion(PlatformName.iOS, 8, 0, throwIfOtherPlatform: false); TestRuntime.AssertSystemVersion(PlatformName.MacOSX, 10, 10, throwIfOtherPlatform: false); using (var dg = new DispatchGroup()) { var called = false; var callback = new Action(() => called = true); using (var block = new DispatchBlock(callback)) { dg.Notify(DispatchQueue.MainQueue, block); TestRuntime.RunAsync(DateTime.Now.AddSeconds(5), () => { }, () => called); Assert.IsTrue(called, "Called"); } } }
// Creates a dispatch group, adds all of the rooms to the zone, and runs the provided completion once all rooms have been added. void AddSelectedRoomsToZoneWithCompletionHandler(Action completionHandler) { var group = DispatchGroup.Create(); foreach (var room in selectedRooms) { group.Enter(); HomeZone.AddRoom(room, error => { if (error != null) { DisplayError(error); } group.Leave(); }); } group.Notify(DispatchQueue.MainQueue, completionHandler); }
List <Activity> CreateActivityDataWithActivities(CMMotionActivity[] activities, Action completionHandler) { var results = new List <Activity> (); var group = DispatchGroup.Create(); var queue = new DispatchQueue("resultQueue"); var filteredActivities = activities.Where(activity => activity.HasActivitySignature() && !activity.Stationary && activity.Confidence != CMMotionActivityConfidence.Low).ToArray <CMMotionActivity> (); var activitySegments = FindActivitySegments(filteredActivities); foreach (var segment in activitySegments) { group.Enter(); pedometer.QueryPedometerData(segment.Item1.StartDate, (NSDate)segment.Item2, (pedometerData, error) => { queue.DispatchAsync(() => { var activity = new Activity(segment.Item1, ((DateTime)segment.Item1.StartDate).ToLocalTime(), segment.Item2.ToLocalTime(), pedometerData); results.Add(activity); }); if (error != null) { HandleError(error); } group.Leave(); }); } group.Notify(DispatchQueue.MainQueue, () => { queue.DispatchSync(() => { RecentActivities = results; RecentActivities.Reverse(); completionHandler?.Invoke(); }); }); return(results); }
private void SetupEditingAndPlayback() { var path1 = NSBundle.MainBundle.PathForResource("sample_clip1", "m4v"); var path2 = NSBundle.MainBundle.PathForResource("sample_clip2", "mov"); var asset1 = AVAsset.FromUrl(new NSUrl(path1, false)) as AVUrlAsset; var asset2 = AVAsset.FromUrl(new NSUrl(path2, false)) as AVUrlAsset; var dispatchGroup = DispatchGroup.Create(); string[] assetKeysToLoadAndTest = { "tracks", "duration", "composable" }; this.LoadAsset(asset1, assetKeysToLoadAndTest, dispatchGroup); this.LoadAsset(asset2, assetKeysToLoadAndTest, dispatchGroup); // Wait until both assets are loaded dispatchGroup.Wait(DispatchTime.Forever); base.InvokeOnMainThread(() => this.SynchronizeWithEditor()); }
void AddSelectedServices(Action completion) { // Create a dispatch group for each of the service additions. var addServicesGroup = DispatchGroup.Create(); foreach (var service in selectedServices) { addServicesGroup.Enter(); ServiceGroup.AddService(service, error => { if (error != null) { DisplayError(error); } addServicesGroup.Leave(); }); } addServicesGroup.Notify(DispatchQueue.MainQueue, completion); }
private void SetupEditingAndPlayback() { string path1 = NSBundle.MainBundle.PathForResource("sample_clip1", "m4v"); string path2 = NSBundle.MainBundle.PathForResource("sample_clip2", "mov"); var asset1 = AVUrlAsset.FromUrl(new NSUrl(path1, false)) as AVUrlAsset; var asset2 = AVUrlAsset.FromUrl(new NSUrl(path2, false)) as AVUrlAsset; var dispatchGroup = DispatchGroup.Create(); string[] assetKeysToLoadandTest = new string[] { "tracks", "duration", "composable" }; LoadAsset(asset1, assetKeysToLoadandTest, dispatchGroup); LoadAsset(asset2, assetKeysToLoadandTest, dispatchGroup); dispatchGroup.DispatchAsync(DispatchQueue.MainQueue, SynchronizeWithEditor); }
// First removes the characteristic from the `targetValueMap`. // Then removes any `HMCharacteristicWriteAction`s from the action set // which set the specified characteristic. public void RemoveTargetValueForCharacteristic(HMCharacteristic characteristic, Action completion) { /* * We need to create a dispatch group here, because in many cases * there will be one characteristic saved in the Action Set, and one * in the target value map. We want to run the completion closure only one time, * to ensure we've removed both. */ var group = DispatchGroup.Create(); if (targetValueMap.ContainsKey(characteristic)) { // Remove the characteristic from the target value map. group.DispatchAsync(DispatchQueue.MainQueue, () => targetValueMap.Remove(characteristic)); } var actionSet = ActionSet; if (actionSet != null) { var actions = actionSet.Actions.OfType <HMCharacteristicWriteAction> (); foreach (var action in actions) { if (action.Characteristic == characteristic) { // Also remove the action, and only relinquish the dispatch group once the action set has finished. group.Enter(); actionSet.RemoveAction(action, error => { if (error != null) { Console.WriteLine(error.LocalizedDescription); } group.Leave(); }); } } } // Once we're positive both have finished, run the completion closure on the main queue. group.Notify(DispatchQueue.MainQueue, completion); }
protected INativeObject GetINativeInstance(Type t) { var ctor = t.GetConstructor(Type.EmptyTypes); if ((ctor != null) && !ctor.IsAbstract) { return(ctor.Invoke(null) as INativeObject); } if (!NativeObjectInterfaceType.IsAssignableFrom(t)) { throw new ArgumentException("t"); } switch (t.Name) { case "CFAllocator": return(CFAllocator.SystemDefault); case "CFBundle": var bundles = CFBundle.GetAll(); if (bundles.Length > 0) { return(bundles [0]); } else { throw new InvalidOperationException(string.Format("Could not create the new instance for type {0}.", t.Name)); } case "CFNotificationCenter": return(CFNotificationCenter.Darwin); case "CFReadStream": case "CFStream": CFReadStream readStream; CFWriteStream writeStream; CFStream.CreatePairWithSocketToHost("www.google.com", 80, out readStream, out writeStream); return(readStream); case "CFWriteStream": CFStream.CreatePairWithSocketToHost("www.google.com", 80, out readStream, out writeStream); return(writeStream); case "CFUrl": return(CFUrl.FromFile("/etc")); case "CFPropertyList": return(CFPropertyList.FromData(NSData.FromString("<string>data</string>")).PropertyList); case "DispatchData": return(DispatchData.FromByteBuffer(new byte [] { 1, 2, 3, 4 })); case "AudioFile": var path = Path.GetFullPath("1.caf"); var af = AudioFile.Open(CFUrl.FromFile(path), AudioFilePermission.Read, AudioFileType.CAF); return(af); case "CFHTTPMessage": return(CFHTTPMessage.CreateEmpty(false)); case "CFMutableString": return(new CFMutableString("xamarin")); case "CGBitmapContext": byte[] data = new byte [400]; using (CGColorSpace space = CGColorSpace.CreateDeviceRGB()) { return(new CGBitmapContext(data, 10, 10, 8, 40, space, CGBitmapFlags.PremultipliedLast)); } case "CGContextPDF": var filename = Environment.GetFolderPath(Environment.SpecialFolder.CommonDocuments) + "/t.pdf"; using (var url = new NSUrl(filename)) return(new CGContextPDF(url)); case "CGColorConversionInfo": var cci = new GColorConversionInfoTriple() { Space = CGColorSpace.CreateGenericRgb(), Intent = CGColorRenderingIntent.Default, Transform = CGColorConversionInfoTransformType.ApplySpace }; return(new CGColorConversionInfo((NSDictionary)null, cci, cci, cci)); case "CGDataConsumer": using (NSMutableData destData = new NSMutableData()) { return(new CGDataConsumer(destData)); } case "CGDataProvider": filename = "xamarin1.png"; return(new CGDataProvider(filename)); case "CGFont": return(CGFont.CreateWithFontName("Courier New")); case "CGPattern": return(new CGPattern( new RectangleF(0, 0, 16, 16), CGAffineTransform.MakeIdentity(), 16, 16, CGPatternTiling.NoDistortion, true, (cgc) => {})); case "CMBufferQueue": return(CMBufferQueue.CreateUnsorted(2)); case "CTFont": CTFontDescriptorAttributes fda = new CTFontDescriptorAttributes() { FamilyName = "Courier", StyleName = "Bold", Size = 16.0f }; using (var fd = new CTFontDescriptor(fda)) return(new CTFont(fd, 10)); case "CTFontCollection": return(new CTFontCollection(new CTFontCollectionOptions())); case "CTFontDescriptor": fda = new CTFontDescriptorAttributes(); return(new CTFontDescriptor(fda)); case "CTTextTab": return(new CTTextTab(CTTextAlignment.Left, 2)); case "CTTypesetter": return(new CTTypesetter(new NSAttributedString("Hello, world", new CTStringAttributes() { ForegroundColorFromContext = true, Font = new CTFont("ArialMT", 24) }))); case "CTFrame": var framesetter = new CTFramesetter(new NSAttributedString("Hello, world", new CTStringAttributes() { ForegroundColorFromContext = true, Font = new CTFont("ArialMT", 24) })); var bPath = UIBezierPath.FromRect(new RectangleF(0, 0, 3, 3)); return(framesetter.GetFrame(new NSRange(0, 0), bPath.CGPath, null)); case "CTFramesetter": return(new CTFramesetter(new NSAttributedString("Hello, world", new CTStringAttributes() { ForegroundColorFromContext = true, Font = new CTFont("ArialMT", 24) }))); case "CTGlyphInfo": return(new CTGlyphInfo("copyright", new CTFont("ArialMY", 24), "Foo")); case "CTLine": return(new CTLine(new NSAttributedString("Hello, world", new CTStringAttributes() { ForegroundColorFromContext = true, Font = new CTFont("ArialMT", 24) }))); case "CGImageDestination": var storage = new NSMutableData(); return(CGImageDestination.Create(new CGDataConsumer(storage), "public.png", 1)); case "CGImageMetadataTag": using (NSString name = new NSString("tagName")) using (var value = new NSString("value")) return(new CGImageMetadataTag(CGImageMetadataTagNamespaces.Exif, CGImageMetadataTagPrefixes.Exif, name, CGImageMetadataType.Default, value)); case "CGImageSource": filename = "xamarin1.png"; return(CGImageSource.FromUrl(NSUrl.FromFilename(filename))); case "SecPolicy": return(SecPolicy.CreateSslPolicy(false, null)); case "SecIdentity": using (var options = NSDictionary.FromObjectAndKey(new NSString("farscape"), SecImportExport.Passphrase)) { NSDictionary[] array; var result = SecImportExport.ImportPkcs12(farscape_pfx, options, out array); if (result != SecStatusCode.Success) { throw new InvalidOperationException(string.Format("Could not create the new instance for type {0} due to {1}.", t.Name, result)); } return(new SecIdentity(array [0].LowlevelObjectForKey(SecImportExport.Identity.Handle))); } case "SecTrust": X509Certificate x = new X509Certificate(mail_google_com); using (var policy = SecPolicy.CreateSslPolicy(true, "mail.google.com")) return(new SecTrust(x, policy)); case "SslContext": return(new SslContext(SslProtocolSide.Client, SslConnectionType.Stream)); case "UIFontFeature": return(new UIFontFeature(CTFontFeatureNumberSpacing.Selector.ProportionalNumbers)); case "NetworkReachability": return(new NetworkReachability(IPAddress.Loopback, null)); case "VTCompressionSession": case "VTSession": return(VTCompressionSession.Create(1024, 768, CMVideoCodecType.H264, (sourceFrame, status, flags, buffer) => { }, null, (CVPixelBufferAttributes)null)); case "VTFrameSilo": return(VTFrameSilo.Create()); case "VTMultiPassStorage": return(VTMultiPassStorage.Create()); case "CFString": return(new CFString("test")); case "DispatchBlock": return(new DispatchBlock(() => { })); case "DispatchQueue": return(new DispatchQueue("com.example.subsystem.taskXYZ")); case "DispatchGroup": return(DispatchGroup.Create()); case "CGColorSpace": return(CGColorSpace.CreateDeviceCmyk()); case "CGGradient": CGColor[] cArray = { UIColor.Black.CGColor, UIColor.Clear.CGColor, UIColor.Blue.CGColor }; return(new CGGradient(null, cArray)); case "CGImage": filename = "xamarin1.png"; using (var dp = new CGDataProvider(filename)) return(CGImage.FromPNG(dp, null, false, CGColorRenderingIntent.Default)); case "CGColor": return(UIColor.Black.CGColor); case "CMClock": return(CMClock.HostTimeClock); case "CMTimebase": return(new CMTimebase(CMClock.HostTimeClock)); case "CVPixelBufferPool": return(new CVPixelBufferPool( new CVPixelBufferPoolSettings(), new CVPixelBufferAttributes(CVPixelFormatType.CV24RGB, 100, 50) )); case "SecCertificate": using (var cdata = NSData.FromArray(mail_google_com)) return(new SecCertificate(cdata)); case "SecCertificate2": using (var cdata = NSData.FromArray(mail_google_com)) return(new SecCertificate2(new SecCertificate(cdata))); case "SecTrust2": X509Certificate x2 = new X509Certificate(mail_google_com); using (var policy = SecPolicy.CreateSslPolicy(true, "mail.google.com")) return(new SecTrust2(new SecTrust(x2, policy))); case "SecIdentity2": using (var options = NSDictionary.FromObjectAndKey(new NSString("farscape"), SecImportExport.Passphrase)) { NSDictionary[] array; var result = SecImportExport.ImportPkcs12(farscape_pfx, options, out array); if (result != SecStatusCode.Success) { throw new InvalidOperationException(string.Format("Could not create the new instance for type {0} due to {1}.", t.Name, result)); } return(new SecIdentity2(new SecIdentity(array [0].LowlevelObjectForKey(SecImportExport.Identity.Handle)))); } case "SecKey": SecKey private_key; SecKey public_key; using (var record = new SecRecord(SecKind.Key)) { record.KeyType = SecKeyType.RSA; record.KeySizeInBits = 512; // it's not a performance test :) SecKey.GenerateKeyPair(record.ToDictionary(), out public_key, out private_key); return(private_key); } case "SecAccessControl": return(new SecAccessControl(SecAccessible.WhenPasscodeSetThisDeviceOnly)); default: throw new InvalidOperationException(string.Format("Could not create the new instance for type {0}.", t.Name)); } }
void loadAsset(AVAsset asset, string[] assetKeysToLoad, DispatchGroup dispatchGroup) { dispatchGroup.Enter (); asset.LoadValuesAsynchronously (assetKeysToLoad, () => { foreach(var key in assetKeysToLoad) { NSError error; if(asset.StatusOfValue(key, out error) == AVKeyValueStatus.Failed) { Console.Error.WriteLine("Key value loading failed for key" + key + " with error: "+ error.ToString()); dispatchGroup.Leave(); } } if(!asset.Composable) { Console.Error.WriteLine("Asset is not composable"); dispatchGroup.Leave(); } Clips.Add(asset); ClipTimeRanges.Add(NSValue.FromCMTimeRange(new CMTimeRange(){ Start = CMTime.FromSeconds(0, 1), Duration = CMTime.FromSeconds(5,1) })); dispatchGroup.Leave(); }); }