Beispiel #1
0
        void OnInstanceDeleted(AwaitableEvent <GlobalDeleteEventArgs> ev)
        {
            Logger.Debug("Instance saved. Initiating publish checks.");

            var type     = ev.Args.EntityType;
            var instance = ev.Args.Entity;

            if (!DependenciesEnitityTypes.Contains(type))
            {
                Logger.Debug("Publish aborted: " + type.Name + " is not of type " + DomainType.Name);
                return;
            }

            ev.Do(async() =>
            {
                if (type == typeof(TDomain))
                {
                    await Publish(instance as TDomain, toDelete: true);
                }
                else
                {
                    await
                        (await FindRelationsOf(instance))
                    .ExceptNull()
                    .Do(async p => await Publish(p));
                }
            });
        }
Beispiel #2
0
        void OnInstanceSaved(AwaitableEvent <GlobalSaveEventArgs> ev)
        {
            var item = ev.Args.Entity;

            Logger.Debug("Instance saved. Initiating publish checks.");

            if (!DependenciesEnitityTypes.Contains(item.GetType()))
            {
                Logger.Debug("Publish aborted: " + item.GetType().Name + " is not of type " + DomainType.Name);
                return;
            }

            ev.Do(async() =>
            {
                if (item is TDomain entity)
                {
                    await Publish(entity);
                }
                else if (item != null)
                {
                    await
                        (await FindRelationsOf(item))
                    .ExceptNull()
                    .Do(async p => await Publish(p));
                }
            });
        }
Beispiel #3
0
        /// <summary>
        ///     Enqueues a n-dimensional kernel to the command queue, which is executed asynchronously.
        /// </summary>
        /// <param name="kernel">The kernel that is to be enqueued.</param>
        /// <param name="workDimension">The dimensionality of the work.</param>
        /// <param name="workUnitsPerKernel">The number of work units per kernel.</param>
        /// <exception cref="OpenClException">
        ///     If the kernel could not be enqueued, then an <see cref="OpenClException" /> is
        ///     thrown.
        /// </exception>
        public Task EnqueueNDRangeKernelAsync(Kernel kernel, int workDimension, int workUnitsPerKernel)
        {
            // Creates a new task completion source, which is used to signal when the command has completed
            TaskCompletionSource <bool> taskCompletionSource = new TaskCompletionSource <bool>();

            // Enqueues the kernel
            Result result = EnqueuedCommandsNativeApi.EnqueueNDRangeKernel(
                Handle,
                kernel.Handle,
                ( uint )workDimension,
                null,
                new[] { new IntPtr(workUnitsPerKernel) },
                null,
                0,
                null,
                out IntPtr waitEventPointer
                );

            // Checks if the kernel was enqueued successfully, if not, then an exception is thrown
            if (result != Result.Success)
            {
                throw new OpenClException("The kernel could not be enqueued.", result);
            }

            // Subscribes to the completed event of the wait event that was returned, when the command finishes, the task completion source is resolved
            AwaitableEvent awaitableEvent = new AwaitableEvent(waitEventPointer);

            awaitableEvent.OnCompleted += (sender, e) =>
            {
                try
                {
                    if (awaitableEvent.CommandExecutionStatus ==
                        CommandExecutionStatus.Error)
                    {
                        taskCompletionSource.TrySetException(
                            new OpenClException(
                                $"The command completed with the error code {awaitableEvent.CommandExecutionStatusCode}."
                                )
                            );
                    }
                    else
                    {
                        taskCompletionSource.TrySetResult(true);
                    }
                }
                catch (Exception exception)
                {
                    taskCompletionSource.TrySetException(exception);
                }
                finally
                {
                    awaitableEvent.Dispose();
                }
            };

            return(taskCompletionSource.Task);
        }
Beispiel #4
0
        private async void TicTacToe()
        {
            Debugger.Break();
            var pointerPressed = new AwaitableEvent <PointerRoutedEventArgs>();

            m_grid.PointerPressed += pointerPressed.Handler;

            while (true)
            {
                // Initialize: Clear board, Turn = X
                ClearBoard();
                Char turn = 'X';

                // Loop until there is a winner (3 in a row)
                for (Boolean winner = false; !winner;)
                {
                    // Wait for PointerPressed event
                    AwaitableEventArgs <PointerRoutedEventArgs> eventArgs = await pointerPressed.RaisedAsync();

                    // If square empty, put symbol in square
                    Point position  = eventArgs.Args.GetCurrentPoint(m_grid).Position;
                    var   textblock = m_grid.GetAt(
                        (Int32)(position.Y / (m_grid.ActualHeight / 3)),
                        (Int32)(position.X / (m_grid.ActualWidth / 3)));
                    if (textblock.Text[0] != c_emptySquare[0])
                    {
                        continue;
                    }
                    textblock.Text = turn.ToString();

                    // If not 3 in a row
                    if (!(winner = Winner(turn)))
                    {
                        // If a tie: Show tie dialog, re-initialize
                        if (Tie())
                        {
                            await new MessageDialog("Tie game").ShowAsync(); break;
                        }

                        // Switch turn (X -> O or O -> X)
                        turn = (turn == 'X') ? 'O' : 'X';
                    }
                    else
                    {
                        // If 3 in a row: Show winner dialog, re-initialize
                        await new MessageDialog(turn + " wins!").ShowAsync();
                    }
                }
            }
        }
Beispiel #5
0
        /// <summary>
        /// Initializes a new instance of the <see cref="IxInstance"/> class.
        /// </summary>
        /// <remarks>
        /// Instance creates in the "Half-instantiated state".
        /// </remarks>
        /// <param name="providerNode">Node that produces instance.</param>
        /// <param name="parentInstance">Direct parent instance.</param>
        /// <param name="creatorTempLock">First temp lock for the creator of a new instance.</param>
        public IxInstance(
            IxProviderNode providerNode,
            [CanBeNull] IIxInstance parentInstance,
            out IIxInstanceLock creatorTempLock)
            : base(providerNode.Host.InstanceTreeSyncRoot)
        {
            ProviderNode              = providerNode;
            _parentInstance           = parentInstance;
            _ownedLocks               = new ProcessableSet <IIxInstanceLock>();
            _locks                    = new ProcessableSet <IIxInstanceLock>();
            _childrenDisposeCompleted = new AwaitableEvent();
            if (parentInstance != null)
            {
                new IxInstanceChildLock(parentInstance, this);
            }

            creatorTempLock = new IxInstancePinLock(this);
            _initTempLock   = creatorTempLock;
        }
Beispiel #6
0
        public async Task AwaitableEventTest()
        {
            // Simple async test.
            using (var ev = new AwaitableEvent())
            {
#pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
                Task.Factory.StartNew(
                    async() =>
                {
                    await Task.Delay(50);

                    // ReSharper disable once AccessToDisposedClosure
                    ev.Set();
                });
#pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed

                await ev;

                ev.IsSet.Should().BeTrue();
            }
        }
Beispiel #7
0
        /// <summary>
        /// Reads the specified memory object associated with this command queue asynchronously.
        /// </summary>
        /// <param name="memoryObject">The memory object that is to be read.</param>
        /// <param name="outputSize">The number of array elements that are to be returned.</param>
        /// <typeparam name="T">The type of the array that is to be returned.</typeparam>
        /// <returns>Returns the value of the memory object.</param>
        public Task <T[]> EnqueueReadBufferAsync <T>(MemoryObject memoryObject, int outputSize) where T : struct
        {
            // Creates a new task completion source, which is used to signal when the command has completed
            TaskCompletionSource <T[]> taskCompletionSource = new TaskCompletionSource <T[]>();

            // Allocates enough memory for the result value
            IntPtr resultValuePointer = IntPtr.Zero;
            int    size = Marshal.SizeOf <T>() * outputSize;

            resultValuePointer = Marshal.AllocHGlobal(size);

            // Reads the memory object, by enqueuing the read operation to the command queue
            IntPtr waitEventPointer;
            Result result = EnqueuedCommandsNativeApi.EnqueueReadBuffer(Handle, memoryObject.Handle, 1, UIntPtr.Zero,
                                                                        new UIntPtr((uint)size), resultValuePointer, 0, null, out waitEventPointer);

            // Checks if the read operation was queued successfuly, if not, an exception is thrown
            if (result != Result.Success)
            {
                throw new OpenClException("The memory object could not be read.", result);
            }

            // Subscribes to the completed event of the wait event that was returned, when the command finishes, the task completion source is resolved
            AwaitableEvent awaitableEvent = new AwaitableEvent(waitEventPointer);

            awaitableEvent.OnCompleted += (sender, e) =>
            {
                try
                {
                    // Checks if the command was executed successfully, if not, then an exception is thrown
                    if (awaitableEvent.CommandExecutionStatus == CommandExecutionStatus.Error)
                    {
                        taskCompletionSource.TrySetException(new OpenClException(
                                                                 $"The command completed with the error code {awaitableEvent.CommandExecutionStatusCode}."));
                        return;
                    }

                    // Goes through the result and converts the content of the result to an array
                    T[] resultValue = new T[outputSize];
                    for (int i = 0; i < outputSize; i++)
                    {
                        resultValue[i] =
                            Marshal.PtrToStructure <T>(IntPtr.Add(resultValuePointer, i * Marshal.SizeOf <T>()));
                    }

                    // Sets the result
                    taskCompletionSource.TrySetResult(resultValue);
                }
                catch (Exception exception)
                {
                    taskCompletionSource.TrySetException(exception);
                }
                finally
                {
                    // Finally the allocated memory has to be freed and the allocated resources are disposed of
                    if (resultValuePointer != IntPtr.Zero)
                    {
                        Marshal.FreeHGlobal(resultValuePointer);
                    }

                    awaitableEvent.Dispose();
                }
            };

            // Returns the task completion source, which resolves when the command has finished
            return(taskCompletionSource.Task);
        }