Home > Blockchain >  Creating a function that returns a generic function
Creating a function that returns a generic function

Time:11-11

obj1.Event takes in Func<CancellationToken,Task>.

This works:

obj1.Event  = async _ =>
{
    try
    {
        await function1(stoppingToken);
    }
    catch (Exception ex)
    {
        Log.Error(ex.ToString());
    }
};

How would one create a function that returns a generic function ex?

obj1.Event  = HandleEvent(function1(stoppingToken))
obj2.Event  = HandleEvent(function2(stoppingToken))
obj3.Event  = HandleEvent(function3(stoppingToken))

Something close to this perhaps but this does not work!

public Func<CancellationToken, Task> HandleEvent<T???>(Func<T> ????)
{
    return func;
}

CodePudding user response:

If your functions all accept a single CancallationToken parameter and return a Task it should be a simple as this:

obj1.Event  = function1;
obj2.Event  = function2;
obj3.Event  = function3;

Note that when Event is invoked, it will pass it's own CancellationToken into your functions.

If you want to pass the stoppingToken instance instead, you can create closures as so:

obj1.Event  = _ => function1(stoppingToken);
obj2.Event  = _ => function2(stoppingToken);
obj3.Event  = _ => function3(stoppingToken);

And if you need extra code to be invoked (e.g. your try..catch in the question), you could do this:

public Func<CancellationToken, Task> HandleEvent(Func<CancellationToken, Task> func)
{
    return async cancellationToken =>
    {
        try
        {
            await func(cancellationToken);
        }
        catch (Exception ex)
        {
            Log.Error(ex.ToString());
        }
    }
}

// Using token from Event
obj1.Event  = HandleEvent(function1);
obj2.Event  = HandleEvent(function2);
obj3.Event  = HandleEvent(function3);

// Using stoppingToken
obj1.Event  = HandleEvent(_ => function1(stoppingToken));
obj2.Event  = HandleEvent(_ => function2(stoppingToken));
obj3.Event  = HandleEvent(_ => function3(stoppingToken));

CodePudding user response:

You could implement the HandleEvent method like this:

public static EventHandler HandleEvent(Func<Task> action)
{
    return async (s, e) =>
    {
        try
        {
            await action();
        }
        catch (Exception ex)
        {
            Log.Error(ex.ToString());
        }
    };
}

Then, assuming that the Event event is of type EventHandler:

public event EventHandler Event;

...you could use the HandleEvent method like this:

obj1.Event  = HandleEvent(() => function1(stoppingToken));

I don't think that it's possible to implement the HandleEvent in a way that would allow you to omit the () =>:

// Not possible
obj1.Event  = HandleEvent(function1(stoppingToken));
  • Related