当前位置: 首页>>代码示例>>C#>>正文


C# Runtime.ActivationData类代码示例

本文整理汇总了C#中Orleans.Runtime.ActivationData的典型用法代码示例。如果您正苦于以下问题:C# ActivationData类的具体用法?C# ActivationData怎么用?C# ActivationData使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。


ActivationData类属于Orleans.Runtime命名空间,在下文中一共展示了ActivationData类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: GrainTimer

        private GrainTimer(Func<object, Task> asyncCallback, object state, TimeSpan dueTime, TimeSpan period, string name)
        {
            var ctxt = RuntimeContext.Current.ActivationContext;
            activationData = (ActivationData) RuntimeClient.Current.CurrentActivationData;

            this.Name = name;
            this.asyncCallback = asyncCallback;
            timer = new AsyncTaskSafeTimer( 
                stateObj => TimerTick(stateObj, ctxt),
                state);
            this.dueTime = dueTime;
            timerFrequency = period;
            previousTickTime = DateTime.UtcNow;
            totalNumTicks = 0;
        }
开发者ID:sbambach,项目名称:orleans,代码行数:15,代码来源:GrainTimer.cs

示例2: DeactivateActivationImpl

        private void DeactivateActivationImpl(ActivationData data, StatisticName statisticName)
        {
            bool promptly = false;
            bool alreadBeingDestroyed = false;
            lock (data)
            {
                if (data.State == ActivationState.Valid)
                {
                    // Change the ActivationData state here, since we're about to give up the lock.
                    data.PrepareForDeactivation(); // Don't accept any new messages
                    ActivationCollector.TryCancelCollection(data);
                    if (!data.IsCurrentlyExecuting)
                    {
                        promptly = true;
                    }
                    else // busy, so destroy later.
                    {
                        data.AddOnInactive(() => DestroyActivationVoid(data));
                    }
                }
                else if (data.State == ActivationState.Create)
                {
                    throw new InvalidOperationException(String.Format(
                        "Activation {0} has called DeactivateOnIdle from within a constructor, which is not allowed.",
                            data.ToString()));
                }
                else if (data.State == ActivationState.Activating)
                {
                    throw new InvalidOperationException(String.Format(
                        "Activation {0} has called DeactivateOnIdle from within OnActivateAsync, which is not allowed.",
                            data.ToString()));
                }
                else
                {
                    alreadBeingDestroyed = true;
                }
            }
            logger.Info(ErrorCode.Catalog_ShutdownActivations_2,
                "DeactivateActivationOnIdle: {0} {1}.", data.ToString(), promptly ? "promptly" : (alreadBeingDestroyed ? "already being destroyed or invalid" : "later when become idle"));

            CounterStatistic.FindOrCreate(statisticName).Increment();
            if (promptly)
            {
                DestroyActivationVoid(data); // Don't await or Ignore, since we are in this activation context and it may have alraedy been destroyed!
            }
        }
开发者ID:Carlm-MS,项目名称:orleans,代码行数:46,代码来源:Catalog.cs

示例3: OnActivationCompletedRequest

        /// <summary>
        /// Invoked when an activation has finished a transaction and may be ready for additional transactions
        /// </summary>
        /// <param name="activation">The activation that has just completed processing this message</param>
        /// <param name="message">The message that has just completed processing. 
        /// This will be <c>null</c> for the case of completion of Activate/Deactivate calls.</param>
        internal void OnActivationCompletedRequest(ActivationData activation, Message message)
        {
            lock (activation)
            {
#if DEBUG
                // This is a hot code path, so using #if to remove diags from Release version
                if (logger.IsVerbose2)
                {
                    logger.Verbose2(ErrorCode.Dispatcher_OnActivationCompletedRequest_Waiting,
                        "OnActivationCompletedRequest {0}: Activation={1}", activation.ActivationId, activation.DumpStatus());
                }
#endif
                activation.ResetRunning(message);

                // ensure inactive callbacks get run even with transactions disabled
                if (!activation.IsCurrentlyExecuting)
                    activation.RunOnInactive();

                // Run message pump to see if there is a new request arrived to be processed
                RunMessagePump(activation);
            }
        }
开发者ID:andrewalex,项目名称:orleans,代码行数:28,代码来源:Dispatcher.cs

示例4: AsyncSendMessage

 /// <summary>
 /// Send an outgoing message
 /// - may buffer for transaction completion / commit if it ends a transaction
 /// - choose target placement address, maintaining send order
 /// - add ordering info & maintain send order
 /// 
 /// </summary>
 /// <param name="message"></param>
 /// <param name="sendingActivation"></param>
 public async Task AsyncSendMessage(Message message, ActivationData sendingActivation = null)
 {
     try
     {
         await AddressMessage(message);
         TransportMessage(message);
     }
     catch (Exception ex)
     {
         if (!(ex.GetBaseException() is KeyNotFoundException))
         {
             logger.Error(ErrorCode.Dispatcher_SelectTarget_Failed,
                 String.Format("SelectTarget failed with {0}", ex.Message),
                 ex);
         }
         MessagingProcessingStatisticsGroup.OnDispatcherMessageProcessedError(message, "SelectTarget failed");
         RejectMessage(message, Message.RejectionTypes.Unrecoverable, ex);
     }
 }
开发者ID:andrewalex,项目名称:orleans,代码行数:28,代码来源:Dispatcher.cs

示例5: HandleIncomingRequest

        /// <summary>
        /// Handle an incoming message and queue/invoke appropriate handler
        /// </summary>
        /// <param name="message"></param>
        /// <param name="targetActivation"></param>
        public void HandleIncomingRequest(Message message, ActivationData targetActivation)
        {
            lock (targetActivation)
            {
                if (targetActivation.State == ActivationState.Invalid)
                {
                    ProcessRequestToInvalidActivation(message, targetActivation.Address, targetActivation.ForwardingAddress, "HandleIncomingRequest");
                    return;
                }

                // Now we can actually scheduler processing of this request
                targetActivation.RecordRunning(message);
                var context = new SchedulingContext(targetActivation);

                MessagingProcessingStatisticsGroup.OnDispatcherMessageProcessedOk(message);
                Scheduler.QueueWorkItem(new InvokeWorkItem(targetActivation, message, context), context);
            }
        }
开发者ID:andrewalex,项目名称:orleans,代码行数:23,代码来源:Dispatcher.cs

示例6: ActivationMayAcceptRequest

 /// <summary>
 /// Determine if the activation is able to currently accept the given message
 /// - always accept responses
 /// For other messages, require that:
 /// - activation is properly initialized
 /// - the message would not cause a reentrancy conflict
 /// </summary>
 /// <param name="targetActivation"></param>
 /// <param name="incoming"></param>
 /// <returns></returns>
 private bool ActivationMayAcceptRequest(ActivationData targetActivation, Message incoming)
 {
     if (!targetActivation.State.Equals(ActivationState.Valid)) return false;
     if (!targetActivation.IsCurrentlyExecuting) return true;
     return CanInterleave(targetActivation, incoming);
 }
开发者ID:andrewalex,项目名称:orleans,代码行数:16,代码来源:Dispatcher.cs

示例7: ReceiveResponse

        private void ReceiveResponse(Message message, ActivationData targetActivation)
        {
            lock (targetActivation)
            {
                if (targetActivation.State == ActivationState.Invalid)
                {
                    logger.Warn(ErrorCode.Dispatcher_Receive_InvalidActivation,
                        "Response received for invalid activation {0}", message);
                    MessagingProcessingStatisticsGroup.OnDispatcherMessageProcessedError(message, "Ivalid");
                    return;
                }
                MessagingProcessingStatisticsGroup.OnDispatcherMessageProcessedOk(message);
                if (Transport.TryDeliverToProxy(message)) return;

                RuntimeClient.Current.ReceiveResponse(message);
            }
        }
开发者ID:andrewalex,项目名称:orleans,代码行数:17,代码来源:Dispatcher.cs

示例8: CallGrainDeactivateAndCleanupStreams

        private async Task<ActivationData> CallGrainDeactivateAndCleanupStreams(ActivationData activation)
        {
            try
            {
                var grainTypeName = activation.GrainInstanceType.FullName;

                // Note: This call is being made from within Scheduler.Queue wrapper, so we are already executing on worker thread
                if (logger.IsVerbose) logger.Verbose(ErrorCode.Catalog_BeforeCallingDeactivate, "About to call {1} grain's OnDeactivateAsync() method {0}", activation, grainTypeName);

                // Call OnDeactivateAsync inline, but within try-catch wrapper to safely capture any exceptions thrown from called function
                try
                {
                    // just check in case this activation data is already Invalid or not here at all.
                    ActivationData ignore;
                    if (TryGetActivationData(activation.ActivationId, out ignore) &&
                        activation.State == ActivationState.Deactivating)
                    {
                        await activation.GrainInstance.OnDeactivateAsync();
                    }
                    if (logger.IsVerbose) logger.Verbose(ErrorCode.Catalog_AfterCallingDeactivate, "Returned from calling {1} grain's OnDeactivateAsync() method {0}", activation, grainTypeName);
                }
                catch (Exception exc)
                {
                    logger.Error(ErrorCode.Catalog_ErrorCallingDeactivate,
                        string.Format("Error calling grain's OnDeactivateAsync() method - Grain type = {1} Activation = {0}", activation, grainTypeName), exc);
                }

                if (activation.IsUsingStreams)
                {
                    try
                    {
                        await activation.DeactivateStreamResources();
                    }
                    catch (Exception exc)
                    {
                        logger.Warn(ErrorCode.Catalog_DeactivateStreamResources_Exception, String.Format("DeactivateStreamResources Grain type = {0} Activation = {1} failed.", grainTypeName, activation), exc);
                    }
                }
            }
            catch(Exception exc)
            {
                logger.Error(ErrorCode.Catalog_FinishGrainDeactivateAndCleanupStreams_Exception, String.Format("CallGrainDeactivateAndCleanupStreams Activation = {0} failed.", activation), exc);
            }
            return activation;
        }
开发者ID:kucheruk,项目名称:orleans,代码行数:45,代码来源:Catalog.cs

示例9: InitActivation

        private async Task InitActivation(ActivationData activation, string grainType, string genericInterface)
        {
            // We've created a dummy activation, which we'll eventually return, but in the meantime we'll queue up (or perform promptly)
            // the operations required to turn the "dummy" activation into a real activation
            ActivationAddress address = activation.Address;

            int initStage = 0;
            // A chain of promises that will have to complete in order to complete the activation
            // Register with the grain directory, register with the store if necessary and call the Activate method on the new activation.
            try
            {
                initStage = 1;
                await RegisterActivationInGrainDirectory(address, !activation.IsMultiActivationGrain);

                initStage = 2;
                await SetupActivationState(activation, grainType);                

                initStage = 3;
                await InvokeActivate(activation);

                ActivationCollector.ScheduleCollection(activation);

                // Success!! Log the result, and start processing messages
                if (logger.IsVerbose) logger.Verbose("InitActivation is done: {0}", address);
            }
            catch (Exception ex)
            {
                lock (activation)
                {
                    activation.SetState(ActivationState.Invalid);
                    try
                    {
                        UnregisterMessageTarget(activation);
                    }
                    catch (Exception exc)
                    {
                        logger.Warn(ErrorCode.Catalog_UnregisterMessageTarget4, String.Format("UnregisterMessageTarget failed on {0}.", activation), exc);
                    }

                    switch (initStage)
                    {
                        case 1: // failed to RegisterActivationInGrainDirectory
                            
                            ActivationAddress target = null;
                            Exception dupExc;
                            // Failure!! Could it be that this grain uses single activation placement, and there already was an activation?
                            if (Utils.TryFindException(ex, typeof (DuplicateActivationException), out dupExc))
                            {
                                target = ((DuplicateActivationException) dupExc).ActivationToUse;
                                CounterStatistic.FindOrCreate(StatisticNames.CATALOG_ACTIVATION_DUPLICATE_ACTIVATIONS)
                                    .Increment();
                            }
                            activation.ForwardingAddress = target;
                            if (target != null)
                            {
                                // If this was a duplicate, it's not an error, just a race.
                                // Forward on all of the pending messages, and then forget about this activation.
                                logger.Info(ErrorCode.Catalog_DuplicateActivation,
                                    "Tried to create a duplicate activation {0}, but we'll use {1} instead. " +
                                    "GrainInstanceType is {2}. " +
                                    "Primary Directory partition for this grain is {3}, " +
                                    "full activation address is {4}. We have {5} messages to forward.",
                                    address,
                                    target,
                                    activation.GrainInstanceType,
                                    ((DuplicateActivationException) dupExc).PrimaryDirectoryForGrain,
                                    address.ToFullString(),
                                    activation.WaitingCount);

                                RerouteAllQueuedMessages(activation, target, "Duplicate activation", ex);
                            }
                            else
                            {
                                logger.Warn(ErrorCode.Runtime_Error_100064,
                                    String.Format("Failed to RegisterActivationInGrainDirectory for {0}.",
                                        activation), ex);
                                // Need to undo the registration we just did earlier
                                scheduler.RunOrQueueTask(() => directory.UnregisterAsync(address),
                                    SchedulingContext).Ignore();

                                RerouteAllQueuedMessages(activation, null,
                                    "Failed RegisterActivationInGrainDirectory", ex);
                            }
                            break;

                        case 2: // failed to setup persistent state
                            
                            logger.Warn(ErrorCode.Catalog_Failed_SetupActivationState,
                                String.Format("Failed to SetupActivationState for {0}.", activation), ex);
                            // Need to undo the registration we just did earlier
                            scheduler.RunOrQueueTask(() => directory.UnregisterAsync(address),
                                SchedulingContext).Ignore();

                            RerouteAllQueuedMessages(activation, null, "Failed SetupActivationState", ex);
                            break;

                        case 3: // failed to InvokeActivate
                            
                            logger.Warn(ErrorCode.Catalog_Failed_InvokeActivate,
                                String.Format("Failed to InvokeActivate for {0}.", activation), ex);
//.........这里部分代码省略.........
开发者ID:kucheruk,项目名称:orleans,代码行数:101,代码来源:Catalog.cs

示例10: SetupActivationInstance

        private void SetupActivationInstance(ActivationData result, string grainType, string genericInterface)
        {
            var genericArguments = String.IsNullOrEmpty(genericInterface) ? null
                : TypeUtils.GenericTypeArgsString(genericInterface);

            lock (result)
            {
                if (result.GrainInstance == null)
                {
                    CreateGrainInstance(grainType, result, genericArguments);
                }
            }
        }
开发者ID:kucheruk,项目名称:orleans,代码行数:13,代码来源:Catalog.cs

示例11: GetOrCreateActivation

        /// <summary>
        /// If activation already exists, use it
        /// Otherwise, create an activation of an existing grain by reading its state.
        /// Return immediately using a dummy that will queue messages.
        /// Concurrently start creating and initializing the real activation and replace it when it is ready.
        /// </summary>
        /// <param name="address">Grain's activation address</param>
        /// <param name="newPlacement">Creation of new activation was requested by the placement director.</param>
        /// <param name="grainType">The type of grain to be activated or created</param>
        /// <param name="genericArguments">Specific generic type of grain to be activated or created</param>
        /// <param name="activatedPromise"></param>
        /// <returns></returns>
        public ActivationData GetOrCreateActivation(
            ActivationAddress address,
            bool newPlacement,
            string grainType,
            string genericArguments,
            out Task activatedPromise)
        {
            ActivationData result;
            activatedPromise = TaskDone.Done;
            lock (activations)
            {
                if (TryGetActivationData(address.Activation, out result))
                {
                    ActivationCollector.TryRescheduleCollection(result);
                    return result;
                }
                
                if (newPlacement && !SiloStatusOracle.CurrentStatus.IsTerminating())
                {
                    // create a dummy activation that will queue up messages until the real data arrives
                    PlacementStrategy placement;
                    int typeCode = address.Grain.GetTypeCode();
                    string actualGrainType = null;

                    if (typeCode != 0) // special case for Membership grain.
                        GetGrainTypeInfo(typeCode, out actualGrainType, out placement);
                    else
                        placement = SystemPlacement.Singleton;

                    if (string.IsNullOrEmpty(grainType))
                    {
                        grainType = actualGrainType;
                    }

                    // We want to do this (RegisterMessageTarget) under the same lock that we tested TryGetActivationData. They both access ActivationDirectory.
                    result = new ActivationData(
                        address, 
                        genericArguments, 
                        placement, 
                        ActivationCollector, 
                        config.Application.GetCollectionAgeLimit(grainType));
                    RegisterMessageTarget(result);
                }
            } // End lock

            // Did not find and did not start placing new
            if (result == null)
            {
                var msg = String.Format("Non-existent activation: {0}, grain type: {1}.",
                                           address.ToFullString(), grainType);
                if (logger.IsVerbose) logger.Verbose(ErrorCode.CatalogNonExistingActivation2, msg);
                CounterStatistic.FindOrCreate(StatisticNames.CATALOG_ACTIVATION_NON_EXISTENT_ACTIVATIONS).Increment();
                throw new NonExistentActivationException(msg) { NonExistentActivation = address };
            }
   
            SetupActivationInstance(result, grainType, genericArguments);
            activatedPromise = InitActivation(result, grainType, genericArguments);
            return result;
        }
开发者ID:kucheruk,项目名称:orleans,代码行数:71,代码来源:Catalog.cs

示例12: UnregisterMessageTarget

        /// <summary>
        /// Unregister message target and stop delivering messages to it
        /// </summary>
        /// <param name="activation"></param>
        public void UnregisterMessageTarget(ActivationData activation)
        {
            activations.RemoveTarget(activation);

            // this should be removed once we've refactored the deactivation code path. For now safe to keep.
            ActivationCollector.TryCancelCollection(activation);
            activationsDestroyed.Increment();

            scheduler.UnregisterWorkContext(new SchedulingContext(activation));

            if (activation.GrainInstance == null) return;

            var grainTypeName = TypeUtils.GetFullName(activation.GrainInstanceType);
            activations.DecrementGrainCounter(grainTypeName);
            activation.SetGrainInstance(null);
        }
开发者ID:kucheruk,项目名称:orleans,代码行数:20,代码来源:Catalog.cs

示例13: RegisterMessageTarget

 /// <summary>
 /// Register a new object to which messages can be delivered with the local lookup table and scheduler.
 /// </summary>
 /// <param name="activation"></param>
 public void RegisterMessageTarget(ActivationData activation)
 {
     var context = new SchedulingContext(activation);
     scheduler.RegisterWorkContext(context);
     activations.RecordNewTarget(activation);
     activationsCreated.Increment();
 }
开发者ID:kucheruk,项目名称:orleans,代码行数:11,代码来源:Catalog.cs

示例14: InvokeActivate

 /// <summary>
 /// Invoke the activate method on a newly created activation
 /// </summary>
 /// <param name="activation"></param>
 /// <returns></returns>
 private Task InvokeActivate(ActivationData activation)
 {
     // NOTE: This should only be called with the correct schedulering context for the activation to be invoked.
     lock (activation)
     {
         activation.SetState(ActivationState.Activating);
     }
     return scheduler.QueueTask(() => CallGrainActivate(activation), new SchedulingContext(activation)); // Target grain's scheduler context);
     // ActivationData will transition out of ActivationState.Activating via Dispatcher.OnActivationCompletedRequest
 }
开发者ID:kucheruk,项目名称:orleans,代码行数:15,代码来源:Catalog.cs

示例15: RegisterActivationInGrainDirectoryAndValidate

        private async Task RegisterActivationInGrainDirectoryAndValidate(ActivationData activation)
        {
            ActivationAddress address = activation.Address;
            bool singleActivationMode = !activation.IsStatelessWorker;

            if (singleActivationMode)
            {
                ActivationAddress returnedAddress = await scheduler.RunOrQueueTask(() => directory.RegisterSingleActivationAsync(address), this.SchedulingContext);
                if (address.Equals(returnedAddress)) return;

                SiloAddress primaryDirectoryForGrain = directory.GetPrimaryForGrain(address.Grain);
                var dae = new DuplicateActivationException
                {
                    ActivationToUse = returnedAddress,
                    PrimaryDirectoryForGrain = primaryDirectoryForGrain
                };

                throw dae;
            }
            else
            {
                StatelessWorkerPlacement stPlacement = activation.PlacedUsing as StatelessWorkerPlacement;
                int maxNumLocalActivations = stPlacement.MaxLocal;
                lock (activations)
                {
                    List<ActivationData> local;
                    if (!LocalLookup(address.Grain, out local) || local.Count <= maxNumLocalActivations)
                        return;

                    var id = StatelessWorkerDirector.PickRandom(local).Address;
                    var dae = new DuplicateActivationException
                    {
                        ActivationToUse = id,
                    };
                    throw dae;
                }
            }
            // We currently don't have any other case for multiple activations except for StatelessWorker.
            //await scheduler.RunOrQueueTask(() => directory.RegisterAsync(address), this.SchedulingContext);
        }
开发者ID:johnazariah,项目名称:orleans,代码行数:40,代码来源:Catalog.cs


注:本文中的Orleans.Runtime.ActivationData类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。