Sunday, 15 March 2015

c# - Sending async mail from SignalR hub -



c# - Sending async mail from SignalR hub -

i need send email result of signalr hub invocation. don't want send execute synchronously, don't want tie websocket connections, caller informed, if possible, if there errors. thought i'd able utilize in hub (minus error handling , other things want do):

public class myhub : hub { public async task dosomething() { var client = new smtpclient(); var message = new mailmessage(/* setup message here */); await client.sendmailasync(message); } }

but discovered won't work; client.sendmailasync phone call throws this:

system.invalidoperationexception: asynchronous operation cannot started @ time. asynchronous operations may started within asynchronous handler or module or during events in page lifecycle.

further investigation , reading has shown me smtpclient.sendmailasync tap wrapper around eap methods, , signalr not allow that.

my question is, there simple way asynchronously send emails straight hub method?

or alternative place email sending code elsewhere? (e.g. have hub queue service-bus message, stand-alone service handle messages , send emails [though i'd have more work way implement notification of results hub's clients]; or have hub create http request webservice email sending).

similar questions here , here.

the signalr team aware of issue, haven't fixed yet. @ point looks it'll go signalr v3.

in meantime, 1 quick hack this:

public async task dosomething() { using (new ignoresynchronizationcontext()) { var client = new smtpclient(); var message = new mailmessage(/* setup message here */); await client.sendmailasync(message); } } public sealed class ignoresynchronizationcontext : idisposable { private readonly synchronizationcontext _original; public ignoresynchronizationcontext() { _original = synchronizationcontext.current; synchronizationcontext.setsynchronizationcontext(new synchronizationcontext()); } public void dispose() { synchronizationcontext.setsynchronizationcontext(_original); } }

c# email signalr async-await smtpclient

No comments:

Post a Comment