You need to have something that allows for a shared context. Controllers by default will have their own.
You could use something like a static
wrapper around a shared context for this to use:
public static class EmailSenderContext {
private static object _locker = new object();
public static bool _canSend = true;
public static bool CanSend() {
var response = false;
lock(_locker) {
response = _canSend;
}
return response;
}
public static void ChangeSendState(bool canSend) {
lock(_locker) {
_canSend = canSend;
}
}
}
public class MyController {
[HttpGet]
public void SendMail()
{
var emails = db.Emails.ToList();
foreach (var email in emails)
{
//code for sending mail here...
if (!EmailSenderContext.CanSend())
break;
}
}
[HttpGet]
public void StopMail()
{
EmailSenderContext.ChangeSendState(false);
}
}
Mind you, this will only work on a single server. The moment you want this to be a global flag, you will need to introduce a database to store the value, and you will want to access that database value each time you check.
This is an OVERLY simplified example, and with many systems, will not work. If this is a small thing for a work project that only runs on a single server with no varying use access, it will work. Again, since this is a shared context, all users will have general access to the value.