I have this method that increases the views of a video when it's watched. If the video of the person who published it reaches 200 views, I send an congrats email to him, but if the email sending DELAYS, I don't want the user to wait for that delay to watch the video. I need to make Video loading not depend on email sending. I have used Task.Run and Task.Factory.StartNew and inside it Parallell I don't have experience with tasks/threads so which is the best way to implement it.
public async Task<ServiceResponse<ViewedVideoDto>> AddVideoView(int candidateVideoId)
{
var video = await _dbcontext.CandidateFiles.Include(x=>x.Candidate).ThenInclude(x=>x.User).FirstOrDefaultAsync(x => x.Id == candidateVideoId);
if (video is null)
{
return new ServiceResponse<ViewedVideoDto>().NotFound(nameof(Resource.VideoEmpty), Resource.VideoEmpty);
}
video.VideoViews += 1;
_dbcontext.Update(video);
await _dbcontext.SaveChangesAsync();
if (video.VideoViews == 200)
{
//Method 1
await Task.Run(() =>
_candidateEmailService.Achieved200VideoViews(video.Candidate.User.Email,
video.Candidate.User.FullName));
//Method 2
Task.Factory.StartNew(() => Parallel.Invoke(() =>
{
_candidateEmailService.Achieved200VideoViews(video.Candidate.User.Email,
video.Candidate.User.FullName);
}));
}
return new ServiceResponse<ViewedVideoDto>()
{
Data = new ViewedVideoDto()
{
VideoId = video.Id
}
};
}
public async Task Achieved200VideoViews(string receiverEmail, string fullName)
{
var candidateTemplate = EmailTemplate.Return(EmailTemplateConst.CanEmailTempFolder, EmailTemplateConst.CanAchieved200VideoViews,fullName);
var innoEmail = new InnoEmail()
{
Email = receiverEmail,
Subject = "Touchpoint after 200 views",
HtmlMessage = candidateTemplate
};
await _emailService.SendAsync(innoEmail);
public async Task<bool> SendAsync(Email email)
{
try
{
var apiKey = _configuration.GetSection("SENDGRID_API_KEY").GetSection("SecretKey").Value;
var Email = _configuration.GetSection("SENDGRID_API_KEY").GetSection("Email").Value;
var client = new SendGridClient(apiKey);
var msg = new SendGridMessage()
{
From = new EmailAddress(Email, "test"),
Subject = email.Subject,
PlainTextContent = null,
HtmlContent = email.HtmlMessage
};
msg.AddTo(new EmailAddress(email.Email));
var response = await client.SendEmailAsync(msg).ConfigureAwait(false);
response.StatusCode.ToString();
return true;
}
catch (System.Exception e)
{
return false;
}
}