拥有同步处理程序和异步处理程序

时间:2017-12-28 12:08:30

标签: c# mediator mediatr

请参阅下面的同步代码:

public class PersonHandler : IRequestHandler<Person, Person>
    {
        public Task<Person> Handle(Person request, CancellationToken cancellationToken)
        {
            request.ID = 1;
            request.Name = "Brian";
            request.Age = 53;
            return Task.FromResult(request);
        }
    }

以及下面的调用代码:

var response2 = mediator.Send(new Person());

这可以按预期工作。请参阅下面的异步代码:

public class PersonHandlerAsync : IRequestHandler<Person, Person>
    {
        public async Task<Person> Handle(Person request, CancellationToken cancellationToken)
        {
            request.ID = 1;
            request.Name = "Brian";
            request.Age = 53;
            var result = await Task.FromResult(request);
            await Task.Delay(30000);
            return result;
        }
    }

以及下面的调用代码:

var response = Task.Run(() => mediator.Send(new Person()));

此代码按预期工作。

是否可以为同一个类(Person)提供两个处理程序,即一个是同步的,另一个是异步的?如果我将两个处理程序类放在我的代码中,那么mediator.send行(mediator.Send(new Person());Task.Run(() => mediator.Send(new Person()));都会调用同步方法。

如何告诉mediatr,使用哪个处理程序类?即用于同步调用的PersonH​​andler和用于异步调用的PersonH​​andlerAsync。

1 个答案:

答案 0 :(得分:0)

你不能按照指定的方式去做。

  

声明您需要的任何处理程序风格 - 同步,异步或可取消异步。从IMediator端,该接口仅为异步,专为现代主机设计。

但是,一种解决方法是创建一个继承自PersonRequest类的PersonRequestAsyncPerson类:

public class Person
{
    public int Id {get; set;}
    public string Name {get; set;}
    public int Age {get; set;}
}

//sync request
public class PersonRequest : Person, IRequest<Person>
{ }

//async request
public class PersonRequestAsync : Person, IRequest<Person>
{ }

然后,你的处理程序看起来像这样:

public class PersonHandler : IRequestHandler<PersonRequest, Person>
{
    public Task<Person> Handle(Person request, CancellationToken cancellationToken)
    {
        request.ID = 1;
        request.Name = "Brian";
        request.Age = 53;
        return Task.FromResult(request);
    }
}

您的async处理程序如下:

public class PersonHandlerAsync : IRequestHandler<PersonRequestAsync, Person>
{
    public async Task<Person> Handle(PersonRequestAsync request, CancellationToken cancellationToken)
    {
        request.ID = 1;
        request.Name = "Brian";
        request.Age = 53;

        //not sure what this is? Hopefully it's just here for demo purposes!
        var result = await Task.FromResult(request);

        await Task.Delay(30000);

        return result;
    }
}

这有效地将PersonRequestAsyncPersonHandlerAsync

联系起来