每n秒更新一次对象状态

时间:2017-06-26 10:13:07

标签: c# multithreading

我有工人阶级,他们的工作是开始循环。我有自己的线程上运行的工作类列表。每隔n秒我就能为每个工人打印一个循环数。 我打算在n秒后打印关于每个工人的信息(例如20秒)
worker1 - noOfLoops - 10
worker2 - noOfLoops - 20
workern - noOfLoops - 30
我怎样才能做到这一点。 代码段

class Program
{
    static void Main(string[] args)
    {
        List<IWorkerClass> workerClasses = new List<IWorkerClass>();
        for (int i = 0;i<5; i++)
        {
            workerClasses.Add(new WorkerClass("worker" + i.ToString()));
        }

        foreach(IWorkerClass wc in workerClasses)
            {
                IWorkerClass temp = wc;
                Thread workerThread = new Thread(() => wc.StartWhileLoop());
                workerThread.Start();
            }
            Console.ReadKey();
        }
    }
    public interface IWorkerClass
    {
        int noOfLoops { get; set; }
        void StartWhileLoop();
    }

    public class WorkerClass : IWorkerClass
    {       
        string _name = string.Empty;
        public WorkerClass(string name)
        {
            this._name = name;
        }
        public int noOfLoops{get;set;}

        public void StartWhileLoop()
        {
            while(true)
            {
                Thread.Sleep(3000);
                noOfLoops += 1;                      
            }
        }
    }
}

1 个答案:

答案 0 :(得分:2)

以下代码保留现有结构,并创建一个新线程,执行ThreadReader每20秒向每个工作人员询问其进度。

using System;
using System.Collections.Generic;
using System.Threading;

class Program
{
    static void Main(string[] args)
    {
        List<IWorkerClass> workerClasses = new List<IWorkerClass>();
        for (int i = 0; i < 5; i++)
        {
            workerClasses.Add(new WorkerClass("worker" + i.ToString()));
        }

        foreach (IWorkerClass wc in workerClasses)
        {
            IWorkerClass temp = wc;
            Thread workerThread = new Thread(() => temp.StartWhileLoop());
            workerThread.Start();
        }

        Thread checkerThread = new Thread(() => ThreadReader(workerClasses));
        checkerThread.Start();

        Console.ReadKey();
    }

    static void ThreadReader(List<IWorkerClass> workers)
    {
        while (true)
        {
            foreach (var worker in workers)
            {
                Console.WriteLine($"{worker.name} - {worker.noOfLoops}");
            }

            Thread.Sleep(20000);
        }
    }
}
public interface IWorkerClass
{
    string name { get; set; }
    int noOfLoops { get; set; }
    void StartWhileLoop();
}

public class WorkerClass : IWorkerClass
{
    public string name { get; set; }
    public WorkerClass(string name)
    {
        this.name = name;
    }
    public int noOfLoops { get; set; }

    public void StartWhileLoop()
    {
        while (true)
        {
            Thread.Sleep(3000);
            noOfLoops += 1;

        }
    }
}