IJob implementation class Execute方法如何使用lock关键字?

IJob implementation class Execute method how to use the lock keyword?

背景:我需要使用定时任务扫描一个数据table(1分钟扫描一次,或者30秒一次),数据table会增加记录,数据table在第三个数据源,以集合为参数做一个Thing,这个事情需要的时间无法确定(一个http请求),之后每次数据库记录修改完成状态,避免下次查询时再次扫描出来。

public class ScanJob : IJob
{
    //Simulation of the data table, the reality of his records will not increase.
    public static List<Person> persions = new List<Person>
    {
        new Person() { Name = "aaa", Status = true },
        new Person() { Name = "bbb", Status = true },
        new Person() { Name = "ccc", Status = true },
        new Person() { Name = "ddd", Status = true },
        new Person() { Name = "eee", Status = true },
    };

    //Intermediate variable, to avoid the previous has not yet ended, the next time has begun
    public static List<string> process = new List<string>();
    public void Execute(IJobExecutionContext context)
    {
        //Equivalent to a database query
        var pers = persions.Where(s => s.Status).ToList();
        //Exclude the object that was executed the previous time
        pers = pers.Where(s=> !process.Contains(s.Name)).ToList();

        Action<List<Person>> doWork = (s) =>
        {
            process.AddRange(s.Select(n => n.Name));//Add to intermediate variable
            DoWork(s);//Do something that can not be expected time (http request)
        };

        doWork.BeginInvoke(pers, (str) =>
        {
            //After DoWork() ends, organize the intermediate variables
            if (pers != null && pers.Count() > 0)
            {
                foreach (var i in pers)
                    process.Remove(i.Name);
            }
        }, null);

        Console.ReadKey();
    }

    public void DoWork(List<Person> _pers)
    {
        Thread.Sleep(1000 * 60 * 1 + 1000 * 10);//Simulate http requests (One minute 10 seconds)

        var firstPer = persions.Where(s => s.Status).FirstOrDefault();
        if (firstPer != null)
        {
            //Simulation to modify the table record
            firstPer.Status = false;
        }
    }
}

由于多个job的触发比较短,而且DoWork()方法执行时间是不可预测的table,可能会导致多个线程同时访问persions变量。如何使用lock语句来处理这个问题?

我把处理集合的三个访问独立于一个class

public static class BaseProcessOperator<T>
{
    static List<string> prevProcess = new List<string>();
    static object obj = new object();
    public static void AddRange(List<string> para)
    {
        lock (obj)
        {
            prevProcess.AddRange(para);
        }
    }

    public static List<string> GetProcesses()
    {
        lock (obj)
        {
            return prevProcess;
        }
    }

    public static void Remove<TParam>(List<TParam> currList, Func<TParam, string> fn)
    {
        if (currList != null && currList.Count() > 0)
        {
            lock (obj)
            {
                foreach (var i in currList)
                {
                    var r = prevProcess.FirstOrDefault(s => s == fn(i));
                    if (!string.IsNullOrWhiteSpace(r))
                        prevProcess.Remove(r);
                }
            }
        }
    }
}

修改ScanJob.cs文件(不再直接使用process设置,而是通过BaseProcessOperator<T>设置)

public void Execute(IJobExecutionContext context)
{
    //Equivalent to a database query
    var pers = persions.Where(s => s.Status).ToList();
    //Exclude the object that was executed the previous time
    pers = pers.Where(s => !BaseProcessOperator<ScanJob>.GetProcesses().Contains(s.Name)).ToList();

    Action<List<Person>> doWork = (s) =>
    {
        BaseProcessOperator<ScanJob>.AddRange(s.Select(n => n.Name).ToList());//Add to intermediate variable
        DoWork(s);//Do something that can not be expected time (http request)
    };

    doWork.BeginInvoke(pers, (str) =>
    {
        //After DoWork() ends, organize the intermediate variables
        BaseProcessOperator<ScanJob>.Remove(pers, (s) => { return s.Name; });
    }, null);

    Console.ReadKey();
}

您可以通过添加 DisallowConcurrentExecution 属性来禁止作业的并发执行

[DisallowConcurrentExecution]
public class ScanJob : IJob
{

}