Func<Task>: A Powerful Delegate for Asynchronous Operation C#

In C#, the declaration "event Func<Task>" represents a delegate type. Let's analyze the meaning of each component.

  • event: This is a C# keyword used to declare events within a class. Events enable communication between objects by allowing an object to notify other objects when a specific action occurs.
  • Func<Task>: This is a declaration of a delegate type. Delegates are function pointers that ensure type safety and can reference methods. Func is a generic delegate type provided by the .NET framework. It represents a method that can take zero or more input parameters and return a value of a specified type. In this case, Func<Task represents a method that takes no parameters and returns a Task object. In C#, Task is a type used for asynchronous operations.

Combining all the elements, "event Func<Task>" declares an event in a C# class that can be subscribed to by other classes. When this event is triggered, it will execute methods that match the signature of Func<Task>. In other words, it will execute methods that return a Task object asynchronously and do not require any parameters.

Below is a straightforward illustration demonstrating its practical application.

Step 1. Create one project in WPF like below.

WPF

WPF Xaml View

<Window x:Class="FunctionBasedEventExample.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:FunctionBasedEventExample"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Grid>
        <Button Content="Test" Height="40" Click="Button_Click"/>
    </Grid>
</Window>

Code behind implementation

using System;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace FunctionBasedEventExample
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        EventHandler eventHandler = new EventHandler();
        Subscriber subscriber = new Subscriber();
        
        public MainWindow()
        {
            InitializeComponent();
            eventHandler.FunctionEvent += EventHandler_FunctionEvent;
        }
        
        private async Task EventHandler_FunctionEvent()
        {
            // Perform the necessary logic when the event is raised
            // For example, updating UI elements, fetching data asynchronously, etc.
            await Task.Delay(1000); // Simulate some asynchronous operation
            MessageBox.Show("event changed fired!");
        }
        
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            eventHandler.TriggerEventChanged();
        }
    }
}

Step 2. Create one helper class like below.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FunctionBasedEventExample
{
    public class EventHandler
    {
        // Declare an event of type Func<Task>
        public event Func<Task> FunctionEvent;

        // Method to raise the event
        public async Task TriggerEventChanged()
        {
            Func<Task> pEventChanged = FunctionEvent;
            if (pEventChanged != null)
            {
                await pEventChanged();
            }
        }
    }

    public class Subscriber
    {
        // Method to be executed when the event is raised
        public async Task HandleEventAsync()
        {
            Console.WriteLine("Event handled asynchronously");
            await Task.Delay(2000); // Simulating some asynchronous operation
        }
    }
}

Step 3. The output will appear as shown below.

Output

Repository path: https://github.com/OmatrixTech/FunctionBasedEventExample