简体   繁体   English

如何在 void 方法中使用异步

[英]How can I use async in void method

I'm developing Asp.Net Core MVC Web Application where I have to check if "EndOfSubscription" of any user is over daily.我正在开发 Asp.Net Core MVC Web 应用程序,我必须每天检查任何用户的“EndOfSubscription”是否结束。 I have to set all users as "Expired" and then send an email to that user.我必须将所有用户设置为“已过期”,然后向该用户发送电子邮件。

The whole process should be implemented as background task.整个过程应该作为后台任务来执行。 Now, it works successfully everyday and it sets the users as "Expired" fine.现在,它每天都能成功运行,并将用户设置为“已过期”。 But my problem is how can I send the email after setting the user as "Expired" immediately.但我的问题是如何在将用户设置为“已过期”后立即发送电子邮件。 Since I have to use (await) to send an email but I Knew that's a bad practice to use (await) for void methods.由于我必须使用 (await) 发送电子邮件,但我知道将 (await) 用于 void 方法是一种不好的做法。 And i tried to do extension method but it didn't works as expected.我试图做扩展方法,但它没有按预期工作。

Here is my startup file.这是我的启动文件。

    public void ConfigureServices(IServiceCollection services)
    {
       ---------- Lines of Code ----------
        services.AddSingleton<IEmailSender, EmailSender>();
        services.Configure<EmailOptions>(Configuration);
        services.AddHangfire(config => config.UseSqlServerStorage(Configuration.GetConnectionString("DefaultConnection")));
        services.AddHangfireServer();
        services.AddScoped<IExpirationJob, ExpirationJob>();
    }

    public void Configure(IApplicationBuilder app,
        IWebHostEnvironment env,
        IRecurringJobManager recurringJobManager,
        IServiceProvider serviceProvider)
    {
         ---------- Lines of Code ----------
        app.UseHangfireDashboard();
        //app.UseHangfireDashboard("/hangfire", new DashboardOptions()
        //{
        //    Authorization = new[] { new CustomAuthorizeFilter() }
        //});
        app.UseAuthentication();
        app.UseAuthorization();

        recurringJobManager.AddOrUpdate(
           "End Users Subscription",
           () => serviceProvider.GetService<IExpirationJob>().SetExpired(),
           Cron.Minutely
           );
    }
}

} }

Here is ExpiredUsersServices file这是 ExpiredUsersServices 文件

 public interface IExpirationJob
{
    void SetExpired();
}


public class ExpirationJob : IExpirationJob
{
    private readonly ApplicationDbContext _db;
    private readonly IEmailSender _emailSender;

    public ExpirationJob(ApplicationDbContext db, IEmailSender emailSender)
    {
        _db = db;
        _emailSender = emailSender;
    }

    public void SetExpired()
    {
        foreach(var item in _db.Institution)
        {
            if (item.EndOfSubscriptionDate <= DateTime.Today) 
            {
                item.Status = SD.StatusExpired;

              //await _emailSender.SendEmailAsync( item.Admin.Email, "Your Account is Expired !", "Your subscription is over and your account is expired."); 
            }
        }
       await _db.SaveChangesAsync();
    }
}

Any help is appreciated.任何帮助表示赞赏。

you can set Task as the return type for your method:您可以将 Task 设置为方法的返回类型:

public interface IExpirationJob
{
    Task SetExpired();
}


public class ExpirationJob : IExpirationJob
{
    private readonly ApplicationDbContext _db;
    private readonly IEmailSender _emailSender;

    public ExpirationJob(ApplicationDbContext db, IEmailSender emailSender)
    {
        _db = db;
        _emailSender = emailSender;
    }

    public async Task SetExpired()
    {
        foreach(var item in _db.Institution)
        {
            if (item.EndOfSubscriptionDate <= DateTime.Today) 
            {
                item.Status = SD.StatusExpired;

              await _emailSender.SendEmailAsync( item.Admin.Email, "Your Account is Expired !", "Your subscription is over and your account is expired."); 
            }
        }
       await _db.SaveChangesAsync();
    }
}

With this approach you'll have to change the caller of this method to await it.使用这种方法,您必须更改此方法的调用者以等待它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM