我试图将一个非常昂贵的计算分解为几个较小的计算,以便通过ExecutorService(如果有)运行它们。
因此,我决定创建多个Callables,它们执行整个计算的特定部分。其中一些计算取决于先前的结果,而其他则没有。
另外,我添加了一种方法,该方法确定如何执行每个可调用对象
public async Task<IActionResult> OnPostAsync(string returnUrl = null)
{
returnUrl = returnUrl ?? Url.Content("~/");
if (ModelState.IsValid)
{
var user = new IdentityUser { UserName = Input.Email, Email = Input.Email };
var result = await _userManager.CreateAsync(user, Input.Password);
if (result.Succeeded)
{
_logger.LogInformation("User created a new account with password.");
await _userManager.AddToRoleAsync(user, "Member");
var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);
var callbackUrl = Url.Page(
"/Account/ConfirmEmail",
pageHandler: null,
values: new { userId = user.Id, code = code },
protocol: Request.Scheme);
await _emailSender.SendEmailAsync(Input.Email, "Confirm your email to get acces to Functionality Matrix pages",
$"Please confirm your account by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>.");
// Block autologin after registration
//await _signInManager.SignInAsync(user, isPersistent: false);
return Redirect("./ConfirmEmailInfo");
}
foreach (var error in result.Errors)
{
ModelState.AddModelError(string.Empty, error.Description);
}
}
// If we got this far, something failed, redisplay form
return Page();
}
}
此方法从另一种方法中被多次调用,该方法将计算结果分成较小的部分。
因此,当使用VisualVM运行计算时,您可以清楚地看到没有线程在执行任何操作,而是GUI线程完成了整个工作。
其他信息:
我正在使用的ExecutorService是private <T> Supplier<T> executeCalculation(Callable<T> callable) {
if (executorService != null) {
Future<T> future = executorService.submit(callable);
return () -> {
try {
return future.get();
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
throw new RuntimeException();
};
} else {
return () -> {
try {
return callable.call();
} catch (Exception e) {
e.printStackTrace();
}
throw new RuntimeException();
};
}
}
调用Executors.newCachedThreadPool();
方法的方法如下:
createCalculation