/// <summary> /// Constructs an instance. /// </summary> /// <param name="owner">owning design object</param> /// <param name="events">events to combine</param> internal MultiEvent(DesignObject owner, IEnumerable <EventSource> events) : base(owner) { Owner = owner; _events = events; _awaiter = new Awaiter(this); }
public void ReturnsImmediatelyForFinishedTask(string status) { server.Reset(); server .Given( Request .Create() .WithPath("/runtime/webhooks/durabletask/instances") .UsingGet() ) .RespondWith( Response .Create() .WithStatusCode(200) .WithBody(@"[ { ""name"": ""MyDurableOrchestrator"", ""instanceId"": ""93581509a6898c110182fedbeef29616"", ""runtimeStatus"": """ + status + @""", ""input"": [], ""customStatus"": null, ""output"": null, ""createdTime"": ""2020-11-03T21:44:45Z"", ""lastUpdatedTime"": ""2020-11-03T21:44:46Z"" } ]") ); var client = new DurableFunctionClient(server.Ports[0]); Func <Task> waiting = () => Awaiter.WaitForInstance(client, "93581509a6898c110182fedbeef29616"); waiting.Should().CompleteWithin(1000.Milliseconds()); }
/// <summary> /// Releases unmanaged and - optionally - managed resources. /// </summary> /// <param name="alsoManaged"><c>true</c> to release both managed and unmanaged resources; /// <c>false</c> to release only unmanaged resources.</param> protected virtual void Dispose(bool alsoManaged) { lock (MethodLock) { if (IsDisposed) { return; } if (alsoManaged == false) { return; } CancelToken.Cancel(); if (AwaiterTask.Status == TaskStatus.Created) { AwaiterTask.Start(); } Awaiter.GetAwaiter().GetResult(); CancelToken.Dispose(); CompletedEvent.Dispose(); AwaiterTask.Dispose(); IsDisposed = true; IsExecuting = false; } }
// Test task static async Task TestAsync(CancellationToken token) { using (var awaiter = new Awaiter()) { WaitOrTimerCallbackProc callback = (a, b) => awaiter.Continue(); IntPtr timerHandle; if (!CreateTimerQueueTimer(out timerHandle, IntPtr.Zero, callback, IntPtr.Zero, 500, 500, 0)) { throw new System.ComponentModel.Win32Exception( Marshal.GetLastWin32Error()); } try { var i = 0; while (true) { token.ThrowIfCancellationRequested(); await awaiter; Console.WriteLine("tick: " + i++); } } finally { DeleteTimerQueueTimer(IntPtr.Zero, timerHandle, IntPtr.Zero); } } }
internal AwaiterMetadata(Awaiter awaiter, AwaiterCollection membership) { Requires.NotNull(awaiter, nameof(awaiter)); this.Awaiter = awaiter; this.Membership = membership; }
public Awaiter OpenAwait() { var ret = new Awaiter(); Open(() => { ret.SetResult(); }); return(ret); }
internal static AwaiterMetadata Released(Awaiter awaiter) { Requires.NotNull(awaiter, nameof(awaiter)); var membership = AwaiterCollection.Released; switch (awaiter.Kind) { case LockKind.Read: membership |= AwaiterCollection.ReadLock; break; case LockKind.UpgradeableRead: membership |= AwaiterCollection.UpgradeableReadLock; break; case LockKind.Write: membership |= AwaiterCollection.WriteLock; break; default: break; } return(new AwaiterMetadata(awaiter, membership)); }
/// <summary> /// Lädt einen Player. /// </summary> /// <param name="universeGuid">Die Guid des Universums.</param> /// <param name="playername">Der Name des Spielers.</param> /// <returns></returns> public Awaiter Load(out Player player, Guid universeGuid, string playername) { //TODO: Später durch Playername ersetzen string file = Path.Combine(GetRoot(), universeGuid.ToString(), "player.info"); player = new Player(); if (!File.Exists(file)) { return(null); } using (Stream stream = File.Open(file, FileMode.Open, FileAccess.Read)) { using (BinaryReader reader = new BinaryReader(stream)) { try { var awaiter = new Awaiter(); awaiter.Serializable = player; player.Deserialize(reader, definitionManager); awaiter.SetResult(player); return(awaiter); } catch (Exception) { // File.Delete(file); } } } return(null); }
/// <summary> /// Lädt eine <see cref="IChunkColumn"/>. /// </summary> /// <param name="universeGuid">GUID des Universums.</param> /// <param name="planet">Index des Planeten.</param> /// <param name="columnIndex">Zu serialisierende ChunkColumn.</param> /// <returns>Die neu geladene ChunkColumn.</returns> public Awaiter Load(out IChunkColumn column, Guid universeGuid, IPlanet planet, Index2 columnIndex) { string file = Path.Combine(GetRoot(), universeGuid.ToString(), planet.Id.ToString(), string.Format(ColumnFilename, columnIndex.X, columnIndex.Y)); column = new ChunkColumn(); if (!File.Exists(file)) { return(null); } try { using (Stream stream = File.Open(file, FileMode.Open, FileAccess.Read)) { using (GZipStream zip = new GZipStream(stream, CompressionMode.Decompress)) { var awaiter = new Awaiter(); awaiter.Serializable = column; awaiter.SetResult(planet.Generator.GenerateColumn(zip, definitionManager, planet.Id, columnIndex)); return(awaiter); } } } catch (IOException) { try { File.Delete(file); } catch (IOException) { } return(null); } }
internal void Forget(Awaiter awaiter) { lock (_stateLock) { _awaiters?.Remove(awaiter); } }
private void Update() { for (int i = 0; i < awaiters.Count; i++) { Awaiter candidate = awaiters[i]; float currentTime = candidate.unscaledTime ? Time.unscaledTime : Time.time; if (currentTime >= candidate.finishTime) { if (candidate.additionalCondition == null || candidate.additionalCondition() == true) { awaiters.RemoveAt(i); if (candidate.progressCallback != null) { candidate.progressCallback(1f); } candidate.resolver.Resolve(); i--; } } else { if (candidate.progressCallback != null) { float startTime = candidate.finishTime - candidate.duration; float progress = Mathf.Clamp01((currentTime - startTime) / candidate.duration); candidate.progressCallback(progress); } } } OnTimeUpdate(Time.time); OnTimeUnscaledUpdate(Time.unscaledTime); }
void ProcessInternal(object o) { var result = task((TIn)o); Awaiter.Set(); Result = result; }
public Awaiter GetTicket(UnityAction <string> ticketCallback = null) { var awaiterUniqueKey = Guid.NewGuid().ToString(); Awaiter newAwaiter = new Awaiter(() => { try { if (actions.Any(a => a.UniqueKey == awaiterUniqueKey)) { actions.Remove(actions.First(a => a.UniqueKey == awaiterUniqueKey)); } if (ticketCallback != null) { ticketCallback.Invoke(awaiterUniqueKey); } if (!actions.Any()) { if (_onAllCompleteUnityAction != null) { _onAllCompleteUnityAction.Invoke(); } if (_onAllCompleteAwaiter != null) { _onAllCompleteAwaiter.Complete(); } } } catch (Exception e) { SuperController.LogError(e.ToString()); } }, awaiterUniqueKey); actions.Add(newAwaiter); return(newAwaiter); }
private static IEnumerable <Awaiter> GetLockStack(Awaiter awaiter) { Requires.NotNull(awaiter, nameof(awaiter)); for (Awaiter?current = awaiter; current != null; current = current.NestingLock) { yield return(awaiter); } }
protected TimerRateLimitProvider(TimeSpan interval, int maxQueuedAuth, IProducerConsumerCollection <TaskCompletionSource <byte> > internalQueue) { Awaiter = (internalQueue = internalQueue ?? GenerateDefaultQueue()) == null ? new TimedTokenProvider <byte>(1, maxQueuedAuth) : new TimedTokenProvider <byte>(1, maxQueuedAuth, internalQueue); Awaiter.AddReadiedAuthTokens(maxQueuedAuth); Timer = new Timer(TriggerAwaiter, null, TimeSpan.Zero, interval); }
public DbTableStorage(StorageFolder folder, string name) { _folder = folder; _indexName = name + ".index"; _dataName = name + ".data"; using (var awaiter = new Awaiter(true)) Open(awaiter); }
public MochiTask <K> ContinueWith <K>(Func <MochiTask <T>, K> func) { var awaiter = Awaiter.Select <Awaiter <T>, T, K>(GetAwaiter(), t => { return(func(new MochiTask <T>(t))); }); return(new MochiTask <K>(awaiter)); }
public static void Initialize() { MainThreadId = Thread.CurrentThread.ManagedThreadId; MainThreadContext = SynchronizationContext.Current; mainThreadAwaiter = new SynchronizationContextAwaiter(MainThreadContext); threadPoolAwaiter = new ThreadPoolContextAwaiter(); nextFrameAwaiter = new NextFrameAwaiter(); }
private static string GetAwaiterGroupId(Awaiter awaiter) { Requires.NotNull(awaiter, nameof(awaiter)); while (awaiter.NestingLock != null) { awaiter = awaiter.NestingLock; } return("LockStack" + GetAwaiterId(awaiter)); }
public MochiTask <T> ContinueWith(Action <T> act) { var awaiter = Awaiter.Select <Awaiter <T>, T, T>(GetAwaiter(), t => { act(t); return(t); }); return(new MochiTask <T>(awaiter)); }
public Tuple <Awaiter, Awaiter <int> > OpenAwait() { var opened = new Awaiter(); var closed = new Awaiter <int>(); Open( () => { opened.SetResult(); }, (result) => { closed.SetResult(result); }); return(Tuple.Create(opened, closed)); }
private static IEnumerable <Awaiter> GetLockStack(Awaiter awaiter) { Requires.NotNull(awaiter, nameof(awaiter)); while (awaiter != null) { yield return(awaiter); awaiter = awaiter.NestingLock; } }
public void Purge() { using (var awaiter = new Awaiter(true)) { Purge(awaiter); Open(awaiter); foreach (var i in _tables) i.Open(awaiter); } }
private Awaiter GetAwaiter(ISerializable serializable, uint packageUId) { var awaiter = new Awaiter { Serializable = serializable }; packages.Add(packageUId, awaiter); return(awaiter); }
public Time(double value, ETimeUnit unit) { if (value < 0.0) { throw new ArgumentException("Negative times are not allowed"); } Value = value; Unit = unit; _awaiter = new Awaiter(this); }
void AwaiterTest() { var awaiter = new Awaiter(); var task = SleepAsync(100, awaiter); awaiter.MoveNext(); Thread.Sleep(500); //while (awaiter.MoveNext()) ; awaiter.Dispose(); task.Dispose(); }
async Task SleepAsync(int milliseconds, Awaiter awaiter) { using (var resource = new Resource()) { Stopwatch timer = Stopwatch.StartNew(); do { await awaiter; }while (timer.ElapsedMilliseconds < milliseconds); } Console.WriteLine("Exit SleepAsync"); }
public Awaitable OpenAsync() { BeginDialogOpen?.Invoke(); if (m_context != null) { throw new Exception(); } m_context = Awaiter.Create(); return(new Awaitable(m_context.Awaiter)); }
/// <summary> /// Constructs an instance. /// </summary> /// <param name="owner">owning design object</param> /// <param name="evt">associated base event</param> /// <param name="pred">predicate function</param> internal PredicatedEvent(DesignObject owner, EventSource evt, Func <bool> pred, Expression description) : base(owner) { Contract.Requires <ArgumentNullException>(evt != null, "evt"); Contract.Requires <ArgumentNullException>(pred != null, "pred"); Contract.Requires <ArgumentNullException>(description != null, "description"); Owner = owner; _baseEvent = evt; _pred = pred; _awaiter = new Awaiter(this); _description = description; }
public static AwaiterContext Create() { var awaiter = new Awaiter(); return(new AwaiterContext { Awaiter = awaiter, Complete = () => { awaiter.m_isCompleted = true; //awaiter.m_continuation(); SynchronizationContext.Current.Post(_ => awaiter.m_continuation(), null); }, SetResult = f => awaiter.m_result = f, }); }
/// <summary> /// </summary> public Awaitable(CancellationToken?ct = null) { m_isCompleted = 0; m_continuations = new List <Action>(); m_continuationLock = new SpinLock(); m_ct = ct; if (m_ct.HasValue) { if (m_ct.Value.CanBeCanceled) { m_ctRegistration = m_ct.Value.Register(Emit); } } m_awaiter = new Awaiter(this); }
private static XElement CreateAwaiterNode(Awaiter awaiter) { Requires.NotNull(awaiter, nameof(awaiter)); var label = new StringBuilder(); label.AppendLine(awaiter.Kind.ToString()); if (awaiter.Options != LockFlags.None) { label.AppendLine("Options: " + awaiter.Options); } Delegate lockWaitingContinuation; #if DESKTOP if (awaiter.RequestingStackTrace != null) { label.AppendLine(awaiter.RequestingStackTrace.ToString()); } #endif if ((lockWaitingContinuation = awaiter.LockRequestingContinuation) != null) { try { foreach (var frame in lockWaitingContinuation.GetAsyncReturnStackFrames()) { label.AppendLine(frame); } } catch (Exception ex) { // Just eat the exception so we don't crash during a hang report. Report.Fail("GetAsyncReturnStackFrames threw exception: ", ex); } } if (label.Length >= Environment.NewLine.Length) { label.Length -= Environment.NewLine.Length; } XElement element = Dgml.Node(GetAwaiterId(awaiter), label.ToString()); return(element); }
internal void Open(Awaiter awaiter) { _indexFile = awaiter.Await(_folder.CreateFileAsync(_indexName, CreationCollisionOption.OpenIfExists)); _dataFile = awaiter.Await(_folder.CreateFileAsync(_dataName, CreationCollisionOption.OpenIfExists)); }
public TotemInternalCriticalAwaitable(Func<object, bool> isCompleted, Func<object, object> getResult, ICriticalNotifyCompletion inner) { _awaiter = new Awaiter(isCompleted, getResult, inner); }
void Open(Awaiter awaiter) { _folder = awaiter.Await(_localData.CreateFolderAsync(_path, CreationCollisionOption.OpenIfExists)); }
public void Open() { using (var awaiter = new Awaiter(true)) Open(awaiter); }
void Purge(Awaiter awaiter) { awaiter.Await(_folder.DeleteAsync(StorageDeleteOption.PermanentDelete)); }