【问题标题】:Skipping threads based on parameter, then returning to them later根据参数跳过线程,稍后再返回
【发布时间】:2017-05-15 04:22:58
【问题描述】:

我有一个接受值的方法,如果满足条件,则该操作不应运行 24 小时。但是当它停止时,我想运行其他不满足该条件的线程。

在这个例子中,我在程序开始时创建了 30 个线程。一旦我做了 5 块奶酪,我就需要停下来,因为那太多了。如果有一个地方可以发送在其他线程正在运行时直到时间用完才能执行的线程,那就太好了。 Task.Delay 即使使用 Wait 在这里似乎也不起作用。

这是我的代码示例:

//Stop making cheese when you have enough for the day but continue making others
  public void madeEnoughToday(string cheese)
    {
//Find how much cheese is made based on cheese type.
            DataGridViewRow row = cheeseGV.Rows
                .Cast<DataGridViewRow>()
                .Where(r => 
r.Cells["Cheese"].Value.ToString().Equals(cheese))
                .First();
            if (row.Cells["MadeToday"].Value.Equals(row.Cells["Perday"].Value))
            {
                Task.Delay(30000).Wait();
            }
    }

【问题讨论】:

    标签: multithreading asynchronous synchronization locking semaphore


    【解决方案1】:

    当我需要暂停线程执行时,我使用另一个线程(全局变量或另一个实现) - 为线程的第二个实例调用 Thread.Join() 方法。

    Thread tPause; // global var
    
    private void MyThreadFunc()
    {
        // do something
        if (pauseCondition)
        {
            tPause=new Thread(PauseThread);
            tPause.Start();
            tPause.Join(); // You can specify needed milliseconds, or TimeSpan
            // the subsequent code will not be executed until tPause.IsAlive == true
            // IMPORTANT: if tPause == null during Join() - an exception occurs
        }
    }
    private void PauseThread()
    {
        Thread.Sleep(Timeout.Infinite); // You can specify needed milliseconds, or TimeSpan
    }
    
    private void Main()
    {
        // any actions  
        Thread myThread=new Thread(MyThreadFunc);
        myThread.Start();
        // any actions
    
    }
    

    有很多方法可以实现这一点。 如果要继续执行线程,可以为暂停线程实例调用Thread.Abort()方法,或者为暂停线程使用复杂的函数构造。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-12-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-04
      相关资源
      最近更新 更多