如何为每个函数调用重新启动循环

时间:2019-05-16 09:55:12

标签: c#

我正在尝试在调用该函数时停止循环。假设首先我调用一个正在运行的函数,然后再次调用该函数,则我需要中断第一个被调用的循环并重新启动该循环。

 public void HitTimer(int leagueid,int dposition,int teamid,int round)
    {
        //if (_hubContext == null)
        //{
        //  _hubContext = GlobalHost.ConnectionManager.GetHubContext<NotificationHub>();
        // }


        int m = 1;

        for (int k = 1; k < 91; k++)
        {

            System.Threading.Thread.Sleep(1000);
            if (k == 90)
            {
                AutoAddDraftPlayer(leagueid, dposition,teamid,round); 

            }
            else if (_hubContext != null)
            {

                    _hubContext.Clients.All.broadcastTime(90 - k, leagueid, teamid, round);



                //hubContext.Clients.Client(Context.ConnectionId).broadcastTime(90 - k);
                //Clients.Caller.broadcastTime(90 - k);
            }
            m++;
        }
    }

我的代码在上面,让我知道如何解决

1 个答案:

答案 0 :(得分:0)

您可以将其重构为基于Task,然后如果再次调用该方法,则使用取消令牌来取消第一个任务。有关如何执行所有这些操作的详细信息,请参见:https://docs.microsoft.com/en-us/dotnet/standard/parallel-programming/task-cancellation

static tokenSource = new CancellationTokenSource();
static CancellationToken ct = tokenSource.Token;
static Task task = null;

public void HitTimer(int leagueid,int dposition,int teamid,int round)
{
    if (task != null)
        tokenSource.Cancel();

    try
    {
        if (task != null)
            task.Wait();
    }
    catch (AggregateException e)
    {
        foreach (var v in e.InnerExceptions)
            Console.WriteLine(e.Message + " " + v.Message);
    }

    task = Task.Factory.StartNew(() => DoLoop(leagueid, dposition, teamid, round), tokenSource.Token)
}

public void DoLoop(int leagueid,int dposition,int teamid,int round)
{
    int m = 1;
    for (int k = 1; k < 91; k++)
    {
        if (ct.IsCancellationRequested)
        {
            break;
        }

        System.Threading.Thread.Sleep(1000);
        if (k == 90)
        {
            AutoAddDraftPlayer(leagueid, dposition,teamid,round); 

        }
        else if (_hubContext != null)
        {

                _hubContext.Clients.All.broadcastTime(90 - k, leagueid, teamid, round);



            //hubContext.Clients.Client(Context.ConnectionId).broadcastTime(90 - k);
            //Clients.Caller.broadcastTime(90 - k);
        }
        m++;
    }
}