none
Control Multithreading for some jobs RRS feed

  • Question

  • hi all,

       I wrote a Windows Service which takes xml files from a folder and insert the data into the database. The xml is created from other service aand i skipped th details here as the scope of that service is not need here.

      My Service use FileWatcher to check the new xml. when a new xml created i added the xml file name to the generic list. In the timer event i loop the generic list and check the access of that xml. IF access is ok just give to ThreadPool.QueueUserWorkItem method. The function calling this method has the responsibility to read the xml file and process to the database. It is working fine now.

      Now suddenly i have problem when processing simultaneously. Actually the xml have different set of data identified using a unique code(Hex code). My scenario is i have 2 hex codes 10 and 11. xml type 10 means this is a start of something so it creates an entry in the table with start time. 11 type is stop and the data update the old entry by putting stop time. Now the problem is when 10 and 11 created in a seconds time and it processed in separate threads, sometime 11 type is processed before 10 type. This creates data error. Can anyone guid me for this. If i use sequential the xml in the folder cumulate more and more as the xml is created from more than one sources. I need to control this special set of type only as sequntial. Any way to handle this type of situation or any other concept i need to implement?

    Sunday, August 5, 2012 3:31 PM

All replies

  • Hello akhilrajau,

    If everything happens inside the same process (but multiple threads) you can use the lock statement to make your resource thread-safe.

    http://msdn.microsoft.com/en-us/library/c5kehkcz(v=vs.80).aspx

    Everything inside a lock block is guaranteed to be thread safe.

    You can, inside that same lock block, write code to verify that type 10 is processed before type 11.

    Monday, August 20, 2012 6:03 PM
  • hi Steve,

     Thanks for the response, Actually i call ThreadPool.QueueUserWorkItem method in the timer event. In the timer i loop through each file in the generic list and call the process method using this ThreadPool.QueueUserWorkItem by passing file name as parameter. So each file is processed in each thread. Where i use this lock statement ? Can you help on this?

    The link you provided is not working..


    • Edited by akhilrajau Tuesday, August 21, 2012 1:13 AM
    Tuesday, August 21, 2012 1:12 AM
  • If I understand the problem, you could create a thread safe list of processing files and lock access to that. I.e. only assign work to a file that isn't in your list.

    http://pauliom.wordpress.com

    Tuesday, August 28, 2012 8:59 PM