简体   繁体   中英

How can I start and stop a looping thread in ASP MVC 4?

I'm working on a simple application that hooks into Wirecast, a streaming software, and forces it to change it source every X seconds. I thought that this would be a good way for me to learn ASP MVC 4, but I'm not very familiar with it and have run into some problems. I'd like the user to be able to enable and disable the loop by selecting a radio button and hitting "Apply", or something similar. Starting the loop works fine, but I'm unable to end it. The way I'm trying to do this is to create a thread that runs the loop and start the thread when the user selects the "Enable Loop" radio button, and abort the thread when they select "Disable Loop". I can see that the Abort method is getting called, but the thread is still running. The relevant code is below:

public Thread loop = new Thread(new ThreadStart(ThreadLoop));

[HttpPost]
public ActionResult Loop(Models.Loop model)
{

    if (model.doLoop == true)
    {
        loop.Start();
    }
    else
    {
        loop.Abort();
    }

    return View();
}

public static void ThreadLoop()
{
    object oWirecast = GetWirecast();
    object oDocument = Late.Invoke(oWirecast, "DocumentByIndex", 1);
    object oNormalLayer = Late.Invoke(oDocument, "LayerByName", "normal");
    shotCount = (int)Late.Invoke(oNormalLayer, "ShotCount");
    int shot = 0;

    while (true)
    {
        shot = shot + 1;
        if (shot > shotCount)
        {
            shot = shot % shotCount;
        }
        int shot_id = (int)Late.Invoke(oNormalLayer, "ShotIDByIndex", shot);
        Late.Set(oNormalLayer, "ActiveShotID", shot_id);
        Late.Invoke(oNormalLayer, "Go");
        Thread.Sleep(3000);
    }
}

So, if you see any problems with this, or can point me in the right direction, I'd love your help. If I can help you help me in any way, just let me know. Thank you!

the DefaultControllerFactory of ASP.NET MVC is not thread safe, every request creates a new controller instance

see http://msdn.microsoft.com/en-us/library/system.web.mvc.defaultcontrollerfactory.aspx

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM