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);
}
}