简体   繁体   中英

main thread timer Vs Thread

i have a windows service that starts a timer on the main thread. 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. The processing can take 10 minutes for example. (lets call this operation A)

I also have a thread that gets spawned via WCF on the same service which updates the xml file. (lets call this operation B)

What is happening is that Operation A is running and Operation B runs to completion before Operation A is completed. The end result being that operation A overwrites all the work that operation B completed.

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

  2. When Operation B is started,If operation A is running, wait for operation A to complete then execute Operation 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)?

thanks Damo

This is easily solved by using the lock statement in C#.

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.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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