c# - How to proceed with Task, await and async in background -
i'm facing situation need understand how proceed properly.
i have action kind of form budget. after user fills fields, user save budget pressing send button.
the send button save data , then, send e-mail companies. when companies, mean around 1000 companies.
but, problem when press button send, page locked when sending e-mails companies , after sending e-mail companies, website return view.
what is, when user press send button, websites saves budget, start send e-mail in background, , instantly return view user, however, while this, website sending e-mails in background 1000 companies.
how did this? here signature of methods:
public async task<partialviewresult> enviarproposta(postorcamentoservicoproposta proposta) { // persist budget savedata(proposta); // companies... var companies = getcompanies(proposta); foreach (var company in companies) await emailfactory.sendbudget(proposta, company).sendasync(); return partialview(proposta); } sendasync async method of smtp.
the question is, how simple throw send e-mail method background , return view, without waiting sending complete?
the second problem i'm using framework convert view in email, so, we'll need context of controller.
should use task.factory.startnew?
should use thread?
considerations: unfortunately, asynchronous controller actions not in scenario, because not yield response user while waiting asynchronous operation complete. solve internal issues related thread pooling , application capacity.
since you're hosting via asp.net, proper way bit complicated.
queuing work via thread doesn't notify runtime there work done. means when app domain recycled (which done time time without intervention), queued work not guaranteed finish. if doesn't concern you, proceed queuing background task.
the "proper" way persist work somehow (message queue, sql server, etc...) , have host run it.
see blog post more details/possible solutions.
Comments
Post a Comment