Skip to content

Activities

Nill edited this page Dec 28, 2021 · 4 revisions

An Activity is an immutable record object representing additional metadata and scope that is attached to a Context.

The Activity property of Context can be used to access the current activity, if there is one. Activities are stored in the ContextFrame, so while multiple Activities can be active, only the top-most Activity is exposed via Context.Activity.

For example, let's imagine you are in the middle of executing the Telegram sendPhoto method in response to a user on Telegram issuing the /test command to your Bot which comes in via a webhook; your Context stack (and the associated Activity property) might look like this:

# Context.Component    Context.Activity    Provides Access To ...
-----------------------------------------------------------------
0 "Root"               null
1 "Webhook"            WebhookActivity     HttpContext, Raw inbound JSON
2 "Update[TestBot]"    UpdateActivity      Update instance
3 "Command[test]"      CommandActivity     Update, Command, CommandEventArgs
4 "Method[sendPhoto]"  MethodActivity      MethodName, Verb, Raw outbound JSON, ...

As additional Metadata

Activities can be used as a strongly-typed way to access transient metadata that's already attached to the Context.

if (Context.Current.Activity is UpdateActivity u)
	DoSomething(u.Update);   // We have access to the Update object

if (Context.Current.Activity is CommandActivity c)
	Debug.Write($"Comand is {c.Name}"); // Access to the Command instance
	Debug.Write($"Args is {c.EventArgs}"); // Ambient access to the CommandEventArgs object

As a Lifetime

Activities also implement IScopeLifetime, which means they can be used as the source of lifetime for things such as component instance lifetimes or event subscription scope.

Activity lifetimes are valid beginning from when they are pushed onto the Context stack and are set to inactive when they are popped from the stack.

Activities vs EventArgs

Activities and EventArgs often provide access to the same types of event-driven case-specific details, however:

  • Activities are immutable and cannot be constructed without all necessary information
  • Activities track whether or not they are currently active or completed
  • Activities can be the source of lifetime for other components
  • Activities themselves provide no mechanism to cancel further event processing or suppress default behavior (such as the Handled property on many EventArgs classes)
  • Activities often provide access to the corresponding EventArgs object, such as CommandActivity.EventArgs, allowing the data in EventArgs types to be used even outside the invocation of an event handler.
  • Components can be scoped to the currently executing Activity

Clone this wiki locally