I have a Pub/Sub class that will call Notify()
when published and that Notify()
could take around 10 seconds, so I need to make sure that this does not block the UI.
public static class NotificationService
{
private static Dictionary<string, INotification> Observers { get; }
static NotificationService()
{
Observers = new Dictionary<string, INotification>();
}
public static void Publish(string title, string requester)
{
foreach (var observer in Observers)
{
var notification = observer.Value;
new Thread(() =>
{
Thread.CurrentThread.IsBackground = true;
notification.Notify(title, requester);
}).Start();
}
}
public static void Subscribe(INotification notification)
{
INotification notificationValue;
if (Observers.TryGetValue(notification.NotificationName, out notificationValue))
{
// Observer already exists
return;
}
Observers[notification.NotificationName] = notification;
}
public static void UnSubscribe(INotification notification)
{
INotification notificationValue;
if (!Observers.TryGetValue(notification.NotificationName, out notificationValue))
{
// Observer doesn't exists
return;
}
Observers.Remove(notification.NotificationName);
}
}
INotification
public interface INotification
{
string NotificationName { get; }
bool Notify(string title, string requester);
}
Example implementation of INotification
public class EmailMessageNotification : INotification
{
public EmailMessageNotification(EmailNotificationSettingsService settings)
{
EmailNotificationSettings = settings;
}
private EmailNotificationSettingsService EmailNotificationSettings { get; }
public string NotificationName => "EmailMessageNotification";
public bool Notify(string title, string requester)
{
var configuration = GetConfiguration();
if (!ValidateConfiguration(configuration))
{
return false;
}
var message = new MailMessage
{
IsBodyHtml = true,
To = { new MailAddress(configuration.RecipientEmail) },
Body = $"User {requester} has requested {title}!",
From = new MailAddress(configuration.EmailUsername),
Subject = $"New Request for {title}!"
};
try
{
using (var smtp = new SmtpClient(configuration.EmailHost, configuration.EmailPort))
{
smtp.Credentials = new NetworkCredential(configuration.EmailUsername, configuration.EmailPassword);
smtp.EnableSsl = configuration.Ssl;
smtp.Send(message);
return true;
}
}
catch (SmtpException smtp)
{
Log.Fatal(smtp);
}
catch (Exception e)
{
Log.Fatal(e);
}
return false;
}
private EmailNotificationSettings GetConfiguration()
{
// Gets and Returns Config
}
private bool ValidateConfiguration(EmailNotificationSettings settings)
{
// Do some validation
}
Can anyone see anything wrong with this?