Events And Delegates In Class Library And Worker Service

Events and delegates are main core concept in .net framework for long running processes. Will have an example of two different projects to show the demo of events and delegates.

In my project am going to create one Class library and one Worker service. The service will consider a long running process. Also, process starts from service and it will call the Class library (DLL) by using instances.

Once the DLL(Dynamic Link Library) starts processing functionalities can't return all responses at the end of execution. While running DLL itself some of status or updates required in the service end. In such cases events and delegates will help to update the status to end point of application.

Event starts from service here. Event was handled in class Library (DLL) with the help of delegates. In a long running process events are triggered from anywhere, Like from web forms/web applications/Windows application/service. That event will be sent by delegates and event handler will reply to the response.

The response may be needed from front end part or Database updates. Events handler response like status can be saved in DB also based on requirement. For output case status will print here in a console window.

Create a new project with worker service and class library.

Events And Delegates In Class Library And Worker Service

Events And Delegates In Class Library And Worker Service

Class library DLL is referred in Worker service project.

Events And Delegates In Class Library And Worker Service

Events and Delegates syntax

<Access Modifier> delegate <Return Type> <Delegate Name> (Parameter);

Example

public delegate void MessageToService(string Status);
<Access Modifier> event <Delegate Name> <Event Name>;

Example

public event MessageToService StatusMessageToService;

Worker service code part is below.

using ClassLibrary;
using static ClassLibrary.Class1;
namespace WorkerService {
    public class Worker: BackgroundService {
        private readonly ILogger < Worker > _logger;
        public Worker(ILogger < Worker > logger) {
            _logger = logger;
        }
        protected override async Task ExecuteAsync(CancellationToken stoppingToken) {
            Class1 obj = new Class1();
            obj.StatusMessageToService += new MessageToService(eventHandler);
            while (!stoppingToken.IsCancellationRequested) {
                obj.method();
                _logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now);
                await Task.Delay(1000, stoppingToken);
            }
        }
        void eventHandler(string Status) {
            Console.WriteLine(Status);
        }
    }
}

Class library (DLL) 

namespace ClassLibrary
{
    public class Class1
    {
        public delegate void MessageToService(string Status);
        public event MessageToService StatusMessageToService;
        
        public void method()
        {
            StatusMessageToService("Method1 processing");
            method2();
            for (int i = 1; i <4 ; i++)
            {
                StatusMessageToService(i+"processing");
            }

        }
        private void method2()
        {
            StatusMessageToService("Method2 processing");
        }
    }
}

Output

Method1 processing
Method2 processing
1processing
2processing
3processing
info: WorkerService.Worker[0]
      Worker running at: 12/20/2022 14:46:14 +05:30


Similar Articles