从SignalR枢纽异步发送邮件 [英] Sending async mail from SignalR hub
问题描述
我需要发送电子邮件作为SignalR枢纽调用的结果。我不想发送同步执行,因为我不想占用的WebSocket连接,但我想来电,被告知如果可能的话,如果有任何错误。我想我可以使用像这样轮毂(减去错误处理,而且我希望它做的所有其他事情):
I need to send an email as a result of a SignalR hub invocation. I don't want the send to execute synchronously, as I don't want to tie up WebSocket connections, but I would like the caller to be informed, if possible, if there were any errors. I thought I'd be able to use something like this in the hub (minus error handling and all other things that I want it to do):
public class MyHub : Hub {
public async Task DoSomething() {
var client = new SmtpClient();
var message = new MailMessage(/* setup message here */);
await client.SendMailAsync(message);
}
}
但很快就发现,它不会工作;在client.SendMailAsync调用抛出这样的:
But soon discovered that it won't work; the client.SendMailAsync call throws this:
System.InvalidOperationException:一个异步操作不能在这个时间开始。异步操作只能在异步处理程序或模块内或在在页面生命周期的某些事件来启动。
System.InvalidOperationException: An asynchronous operation cannot be started at this time. Asynchronous operations may only be started within an asynchronous handler or module or during certain events in the Page lifecycle.
进一步的调查和阅读指示我,SmtpClient.SendMailAsync围绕EAP方法TAP包装,而SignalR不允许。
Further investigation and reading has shown me that SmtpClient.SendMailAsync is a TAP wrapper around EAP methods, and that SignalR does not allow that.
我的问题是,有没有简单的方法来异步直接从枢纽方法发送的电子邮件?
My question is, is there any simple way to asynchronously send the emails directly from a hub method?
或者是我把邮件唯一的选择发送code别处? (例如,有枢纽排队服务总线的消息,那么一个独立的服务可以处理这些信息并发送电子邮件[虽然我也想有更多的工作这种方式来实现结果的通知返回到集线器的客户;或者有轮毂使一个HTTP请求到执行电子邮件发送)一个Web服务。
Or is my only option to place the email sending code elsewhere? (e.g. have the hub queue a service-bus message, then a stand-alone service could handle those messages and send the emails [though I'd also have more work this way to implement notification of results back to the hub's clients]; or have the hub make an HTTP request to a webservice that does the email sending).
推荐答案
该SignalR团队意识到这个问题的,但没有固定的呢。在这一点上,它看起来像它会进入SignalR V3。
The SignalR team is aware of the issue, but haven't fixed it yet. At this point it looks like it'll go into SignalR v3.
在此期间,一个快速的黑客会是这样:
In the meantime, one quick hack would be 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);
}
}
这篇关于从SignalR枢纽异步发送邮件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!