Unable to break while loop immediately on button click c# mvc

狂风中的少年 提交于 2019-12-01 14:49:53

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.

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);
            }
        }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!