简体   繁体   English

取消任务内部的异步任务

[英]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 ? 正如您在任务中看到的那样,我想在该foreach中停止或取消任务,我该怎么做?

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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