IJob实现类Execute方法如何使用lock关键字?

时间:2017-06-25 16:45:12

标签: c# quartz.net

后台:我需要使用计划任务来扫描数据表(1分钟扫描一次,或者可能30秒一次),数据表会增加记录,数据表会在第三个数据源,以集合作为参数来做一件事,这件事所需的时间无法确定(一个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;
        }
    }
}

由于多个作业触发器较短,并且DoWork()方法执行时间不可预测,因此可能导致多个线程同时访问persions变量。如何使用lock语句来处理这个问题?

2 个答案:

答案 0 :(得分:0)

我对处理集合进行了三次访问,而不依赖于类

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();
}

答案 1 :(得分:0)

您可以通过添加DisallowConcurrentExecution属性

来禁止并发执行Job
[DisallowConcurrentExecution]
public class ScanJob : IJob
{

}