问题
I have mvc action method where while loop is running I want to stop that while loop on another button click so I have maintain a flag and set it to false to break loop.
bool flag = true;
public async Demo()
{
while(flag == true)
{
do something...
}
}
now on button click I'm calling one action method to stop the while loop -
public ActionResult StopLoop()
{
flag = false;
Return View("Index")
}
But it is taking almost a minute time to hit this StopLoop
after click on button.
why ? may be all are on same UI page and sharing same homecontroller
any trick i can do ?
i have 2 buttons on one button request while loop start and i want on another button click request loop stop.
回答1:
If you're saying that one request starts the while loop, and you want another request to stop it, then that's not possible with a ASP.NET MVC as it is stateless. Once the view is returned your while loop is no longer running. In your case, it only looks like it's taking a minute for the StopLoop
method to get hit. What's probably really happening is that your while loop is probably running endlessly, IIS kills it, and then the stop loop request is processed.
回答2:
if you want run two tasks parallel, you need to use new thread for second task, also you need to stop second thread conditionally.
CancellationTokenSource TokenSource = new CancellationTokenSource();
CancellationToken Ct = TokenSource.Token;
Task Demo = Task.Run(() =>
{
do
{
Thread.Sleep(1000);
Trace.Write("loop");
} while (!Ct.IsCancellationRequested);
}, Ct);
bool Flag = true;
if (Flag)
{
TokenSource.Cancel();
}
you can see more information about async programming here Creating and running tasks explicitly
and about Task Cancellation
Update
if you want do this in web application you have to run second task in a thread that won't kill after request finished.
public class MvcApplication : System.Web.HttpApplication
{
static Task Demo = null;
static CancellationTokenSource TokenSource = null;
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
TokenSource = new CancellationTokenSource();
CancellationToken Ct = TokenSource.Token;
Demo = Task.Run(() =>
{
do
{
Thread.Sleep(1000);
Trace.Write("loop");
} while (!Ct.IsCancellationRequested);
}, Ct);
}
public static void CancelLoop()
{
TokenSource.Cancel();
}
}
and you have to cancel the second task (contain while loop) with a request. for example:
public class HomeController : Controller
{
public JsonResult ButtonPressed()
{
MvcApplication.CancelLoop();
return Json("canceled", JsonRequestBehavior.AllowGet);
}
}
来源:https://stackoverflow.com/questions/53045087/unable-to-break-while-loop-immediately-on-button-click-c-sharp-mvc