简体   繁体   English

主线程计时器Vs线程

[英]main thread timer Vs Thread

i have a windows service that starts a timer on the main thread. 我有一个Windows服务,在主线程上启动计时器。 The timers job is to load an xml file to memory, do some processing on the values and save the results back to the file. 计时器的工作是将xml文件加载到内存,对值进行一些处理并将结果保存回文件。 The processing can take 10 minutes for example. 例如,处理可能需要10分钟。 (lets call this operation A) (让我们称这个操作为A)

I also have a thread that gets spawned via WCF on the same service which updates the xml file. 我还有一个线程,它通过WCF在更新xml文件的同一服务上生成。 (lets call this operation B) (让我们调用此操作B)

What is happening is that Operation A is running and Operation B runs to completion before Operation A is completed. 发生的事情是操作A正在运行,操作B在操作A完成之前运行完成。 The end result being that operation A overwrites all the work that operation B completed. 最终结果是操作A覆盖了操作B完成的所有工作。

So what i think i need to do is: 所以我认为我需要做的是:

  1. When Operation A is starting,If operation B is running, wait for operation B to complete then execute Operation A 当操作A启动时,如果操作B正在运行,则等待操作B完成然后执行操作A.

  2. When Operation B is started,If operation A is running, wait for operation A to complete then execute Operation B 当操作B启动时,如果操作A正在运行,则等待操作A完成然后执行操作B.

if i could do this i wouldn't have a problem i think. 如果我能做到这一点,我认为我不会有问题。

I hope this makes sense - Is my wait theory the best way to do this? 我希望这是有道理的 - 我的等待理论是最好的方法吗? How can i do this in c# (or whatever the best method is)? 我怎样才能在c#(或者最好的方法)中做到这一点?

thanks Damo 谢谢达莫

This is easily solved by using the lock statement in C#. 通过在C#中使用lock语句可以轻松解决这个问题。

All you'll need is an instance of some object (the type doesn't matter) that both sections of code have access to. 所有你需要的是两个代码段都可以访问的某个对象的实例(类型无关紧要)。

public static void MethodA(object lockObject)
{
    lock(lockObject)
    {
        //code that needs to be accessed by just one thread
    }
}

public static void MethodB(object lockObject)
{
    lock(lockObject)
    {
        //code that needs to be accessed by just one thread
    }
}

If both of these operations are being fired from a timer you should ensure that adding extra waiting doesn't push you to the point where executing the code takes longer than the interval on the timer; 如果这两个操作都是从定时器触发的,那么你应该确保添加额外的等待不会让你到达执行代码的时间超过定时器间隔的时间点。 if you do you'll end up firing off new code quicker than they finish and there will always be more and more instances running. 如果你这样做,你最终会比他们完成更快地解雇新代码,并且总会有越来越多的实例在运行。 (That is solved by having it do nothing if a previous task is still running.) (如果先前的任务仍在运行,则无法解决问题。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM