简体   繁体   中英

cancel async task inside of the task

hi this is may main function

    static void Main(string[] args)
    {   
        foreach(var user in sommodel)
        {
             AsyncContext.Run(() => sf.StartFollowState(5));
        }
    }

and this is task

public class StartFollow
{
    public async Task StartFollowState(long iuid)
    {
        foreach(var user in sommodel)
        {
             if(somthing)
             {
                  //cancel a task
             }
              //do some
        }
        foreach(var user in sommodel)
        {
              //do some
        }
    }
}

as you can see in the task I want to stop or cancel the task in that foreach how can I do that ?

Unfortunately one does not simply cancel a Task. What you could do is 'return' out of the method so that the Task runs into nirvana and then just wait for the Garbage Collector to do the work.

public class StartFollow
{
    public async Task StartFollowState(long iuid)
    {
        foreach(var user in sommodel)
        {
             if(somthing)
             {
                  //cancel a task
                  return;    
             }

             //do some
        }

        foreach(var user in sommodel)
        {
              //do some
        }
    }
}

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