private Hashtable _propertyNumberToPropertyInfoIdx; // номер свойства - индекс в массиве свойств /// <summary> /// При загрузке 1С:Предприятие V8 инициализирует объект компоненты, /// вызывая метод Init и передавая указатель на IDispatch. /// Объект может сохранить этот указатель для дальнейшего использования. /// Все остальные интерфейсы 1С:Предприятия объект может получить, вызвав метод QueryInterface /// переданного ему интерфейса IDispatch. Объект должен возвратить S_OK, /// если инициализация прошла успешно, и E_FAIL при возникновении ошибки. /// Данный метод может использовать интерфейс IErrorLog для вывода информации об ошибках. /// При этом инициализация считается неудачной, если одна из переданных структур EXCEPINFO /// имеет поле scode, не равное S_OK. Все переданные в IErrorLog данные обрабатываются /// при возврате из данного метода. В момент вызова этого метода свойство AppDispatch не определено. /// </summary> /// <param name="connection">reference to IDispatch</param> public void Init([MarshalAs(UnmanagedType.IDispatch)] object connection) { Connect1C = connection; StatusLine = (IStatusLine)connection; AsyncEvent = (IAsyncEvent)connection; ErrorLog = (IErrorLog)connection; }
/// <summary> /// Инициализация компонента /// </summary> /// <param name="connection">reference to IDispatch</param> public void Init( [MarshalAs(UnmanagedType.IDispatch)] object connection) { asyncEvent = (IAsyncEvent)connection; statusLine = (IStatusLine)connection; }
internal static async Task WaitForCommitAsync(IAuditTrail log, IAsyncEvent commitEvent, long index, TimeSpan timeout, CancellationToken token) { for (var timeoutMeasurement = new Timeout(timeout); log.GetLastIndex(true) < index; await commitEvent.Wait(timeout, token).ConfigureAwait(false)) { timeoutMeasurement.ThrowIfExpired(out timeout); } }
public static void load(object AddInObject) { m_AddInObject = AddInObject; // Вызываем неявно QueryInterface m_ErrorInfo = (IErrorLog)AddInObject; m_AsyncEvent = (IAsyncEvent)AddInObject; m_StatusLine = (IStatusLine)AddInObject; }
private static async Task Track(TimeSpan timeout, IAsyncEvent refreshEvent, Action candidateState, CancellationToken token) { //spin loop to wait for the timeout while (await refreshEvent.WaitAsync(timeout, token).ConfigureAwait(false)) { } //timeout happened, move to candidate state candidateState(); }
public Interactor() { like_dispatch = V7Data.V7Object; like_asyncevent = V7Data.AsyncEvent; like_errorlog = V7Data.ErrorLog; like_statusline = V7Data.StatusLine; like_extwndssupport = V7Data.ExtWndsSupport; like_propertyprofile = V7Data.PropertyProfile; }
//Инициализация компоненты void IInitDone.Init([MarshalAs(UnmanagedType.IDispatch)] object connection) { asyncevent = (IAsyncEvent)connection; statusline = (IStatusLine)connection; if (InitEvent != null) { InitEvent(); } }
private static async Task Track(TimeSpan timeout, IAsyncEvent refreshEvent, Action candidateState, params CancellationToken[] tokens) { using var tokenSource = CancellationTokenSource.CreateLinkedTokenSource(tokens); // spin loop to wait for the timeout while (await refreshEvent.WaitAsync(timeout, tokenSource.Token).ConfigureAwait(false)) { } // timeout happened, move to candidate state candidateState(); }
public async Task ParseSystemClientEventAsync() { string data = "650 STATUS_CLIENT NOTICE BOOTSTRAP PROGRESS=14 TAG=handshake SUMMARY=\"Handshaking with a relay\"\r\n"; TorControlReply rawReply = await TorControlReplyReaderTest.ParseAsync(data); IAsyncEvent asyncEvent = AsyncEventParser.Parse(rawReply); BootstrapStatusEvent @event = Assert.IsType <BootstrapStatusEvent>(asyncEvent); Assert.NotNull(@event); }
public async Task ParseCircEventAsync() { string data = "650 CIRC 16 LAUNCHED BUILD_FLAGS=NEED_CAPACITY PURPOSE=GENERAL TIME_CREATED=2021-06-10T05:42:43.808915\r\n"; TorControlReply rawReply = await TorControlReplyReaderTest.ParseAsync(data); IAsyncEvent asyncEvent = AsyncEventParser.Parse(rawReply); CircEvent @event = Assert.IsType <CircEvent>(asyncEvent); Assert.NotNull(@event); }
//Инициализация компоненты void IInitDone.Init([MarshalAs(UnmanagedType.IDispatch)] object connection) { MessageBox.Show("Ошибка", "Попытка деления на ноль", MessageBoxButtons.OKCancel, MessageBoxIcon.Error); asyncevent = (IAsyncEvent)connection; statusline = (IStatusLine)connection; if (InitEvent != null) { InitEvent(); } }
public virtual async Task PublishAsync(IAsyncEvent e, CancellationToken cancellationToken) { var eventType = e.GetType(); var handlerType = typeof(IAsyncEventHandler <>).MakeGenericType(e.GetType()); var handleAsync = (InvokeHandleAsync)_eventHandlerInvokers.GetOrAdd(handlerType, t => CreateHandlerInvoker <InvokeHandleAsync>(eventType, handlerType, "HandleAsync", Expression.Parameter(typeof(CancellationToken), "token"))); foreach (var obj in GetInstances(handlerType)) { await handleAsync(obj, e, cancellationToken); if (cancellationToken.IsCancellationRequested) { return; } } }
/// <summary> /// Initializes a new persistent channel with the specified options. /// </summary> /// <param name="options">The options of the channel.</param> protected PersistentChannel(PersistentChannelOptions options) { maxCount = options.PartitionCapacity; bufferSize = options.BufferSize; location = new DirectoryInfo(options.Location); if (!location.Exists) { location.Create(); } var writer = new PersistentChannelWriter <TInput>(this, options.SingleWriter, options.InitialPartitionSize); var reader = new PersistentChannelReader <TOutput>(this, options.SingleReader); Reader = reader; Writer = writer; readTrigger = new AsyncCounter(writer.Position - reader.Position); }
bool HandleAsyncEvent(EventContext context, IAsyncEvent asyncEvent) { context.Status = EventContextStatus.Waiting; int waiting = RaiseAsync(asyncEvent, () => { context.Node = context.Node?.Next; context.Status = EventContextStatus.Ready; }); if (waiting == 0) { ApiUtil.Assert($"Async event {asyncEvent} not acknowledged. Continuing immediately."); context.Node = context.Node.Next; context.Status = EventContextStatus.Ready; } else if (context.Status == EventContextStatus.Waiting) { _threadContexts.Value.Pop(); return(true); } // If the continuation was called already then continue iterating. return(false); }
bool HandleBoolEvent(EventContext context, IAsyncEvent <bool> boolEvent, IBranchNode branch) // Return value = whether to return. { context.Status = EventContextStatus.Waiting; int waiting = RaiseAsync(boolEvent, result => { #if DEBUG Raise(new LogEvent(LogEvent.Level.Info, $"if ({context.Node.Event}) => {result}")); #endif context.Node = result ? branch.Next : branch.NextIfFalse; // If a non-query event needs to set this it will have to do it itself. This is to allow // things like chest / door events where different combinations of their IAsyncEvent<bool> result // and the LastEventResult can mean successful opening, exiting the screen without success or a // trap has been triggered. if (boolEvent is IQueryEvent) { LastEventResult = result; } context.Status = EventContextStatus.Ready; }); if (waiting == 0) { ApiUtil.Assert($"Async event {boolEvent} not acknowledged. Continuing immediately."); context.Node = context.Node.Next; context.Status = EventContextStatus.Ready; } else if (context.Status == EventContextStatus.Waiting) { // If the continuation hasn't been called then stop iterating for now and wait for completion. _threadContexts.Value.Pop(); return(true); } // If the continuation was called already then continue iterating. return(false); }
/// <summary> /// イベントを購読する。 /// </summary> public static IDisposable Subscribe <T>(this IAsyncEvent <T> e, AsyncHandler <T> handler) { e.Add(handler); return(Disposable.Create(() => e.Remove(handler))); }
public new int RaiseAsync <T>(IAsyncEvent <T> e, Action <T> continuation) => base.RaiseAsync(e, continuation);
public new int RaiseAsync(IAsyncEvent e, Action continuation) => base.RaiseAsync(e, continuation);
public static void Clean() { m_AsyncEvent = null; m_ErrorInfo = null; m_ExtWndsSupport = null; m_PropertyProfile = null; m_StatusLine = null; m_V7Object = null; }
public virtual Task PublishAsync(IAsyncEvent e) { return(PublishAsync(e, CancellationToken.None)); }
public static IDisposable Subscribe <T>(this IAsyncEvent <T> e, Func <Task> handler) { return(Subscribe(e, (_1, _2) => handler())); }
/// <summary> /// Turns caller into idle state until the current event is set. /// </summary> /// <param name="event">An event to synchronize with.</param> /// <param name="timeout">The interval to wait for the signaled state.</param> /// <returns><see langword="true"/> if signaled state was set; otherwise, <see langword="false"/>.</returns> public static Task<bool> WaitAsync(this IAsyncEvent @event, TimeSpan timeout) => @event.WaitAsync(timeout, CancellationToken.None);
/// <summary> /// キャンセルされるまでの間イベントを購読する。 /// </summary> public static void SubscribeUntil <T>(this IAsyncEvent <T> e, CancellationToken ct, Func <Task> handler) { var d = e.Subscribe(handler); ct.Register(d.Dispose); }
/// <summary> /// <see cref="AsyncAction{T1}"/>以外の形式でイベントを購読する。 /// </summary> public static IDisposable Subscribe <T>(this IAsyncEvent <T> e, Action <T> handler) => e.Subscribe((_1, args) => { handler(args); return(Task.CompletedTask); });
/// <summary> /// <see cref="AsyncAction{T1}"/>以外の形式でイベントを購読する。 /// </summary> public static IDisposable Subscribe <T>(this IAsyncEvent <T> e, Func <Task> handler) => e.Subscribe((_1, _2) => handler());
/// <summary> /// Turns caller into idle state until the current event is set. /// </summary> /// <remarks> /// This method can potentially blocks execution of async flow infinitely. /// </remarks> /// <param name="event">An event to synchronize with.</param> /// <param name="token">The token that can be used to abort wait process.</param> /// <returns>A promise of signaled state.</returns> public static Task WaitAsync(this IAsyncEvent @event, CancellationToken token) => @event.WaitAsync(InfiniteTimeSpan, token);
/// <summary> /// Turns caller into idle state until the current event is set. /// </summary> /// <remarks> /// This method can potentially blocks execution of async flow infinitely. /// </remarks> /// <param name="event">An event to synchronize with.</param> /// <returns>A promise of signaled state.</returns> public static Task WaitAsync(this IAsyncEvent @event) => @event.WaitAsync(CancellationToken.None);
internal FollowerState(IRaftStateMachine stateMachine) : base(stateMachine) { refreshEvent = new AsyncAutoResetEvent(false); trackerCancellation = new CancellationTokenSource(); }
/// <summary> /// イベントを購読する。 /// </summary> public static IDisposable Subscribe <T>(this IAsyncEvent <T> e, Func <T, Task> handler) => Subscribe(e, (_1, arg) => handler(arg));
protected override void Init(object connection) { _asyncEvent = (IAsyncEvent)connection; _statusLine = (IStatusLine)connection; }
/// <summary> /// イベントを購読する。 /// </summary> public static IDisposable Subscribe <T>(this IAsyncEvent <T> e, Action <T> handler) => Subscribe(e, (_1, args) => { handler(args); return(Task.FromResult(default(object))); });