Sorry for the abstract question, but I'm looking for some examples / tips / articles about the type of applications that perform some equivalent operations in a loop, and each iteration of the loop should expose its result in a certain part of the time (for example, 10 seconds).
My application synchronizes data between an external WCF service and a local database. At each iteration, the application fetches the changes to the data transfer request to the WCF service and puts the changes into the database and vice versa. One of the most difficult requirements for this application is that iterations should fire every ten seconds.
So here are the problems. How can I guarantee that the iteration will end in no more than 10 seconds?
I assume that this type of application is called real-time applications (real-time OS).
The DAL components that we use randomly affect the connection timeout behavior. Thus, DB operations can take longer than 10 seconds.
Here is a sample code for one iteration:
Stopwatch s1 = new Stopwatch(); s1.Start(); Parallel.ForEach(Global.config.databases, new ParallelOptions { MaxDegreeOfParallelism = -1 }, (l) => { Console.WriteLine("Started for {0}", l.key.name); DB db = new DB(l.connectionString); DateTime lastIterationTS = GetPreviousIterationTS(l.id); ExternalService serv = new ExternalService(l.id); List<ChangedData> ChangedDataDb = db.GetChangedData(DateTime.Now.AddSeconds((lastIterationTS == DateTime.MinValue) ? -300 : -1 * (DateTime.Now - lastIterationTS).Seconds)); List<Data> ChangedDataService = serv.GetModifiedData(); Action syncDBChanges = new Action(() => { // foreach (ChangedData d in ChangedDataDb) { try { // ... // analyzing & syncing } catch (Exception e) { logger.InfoEx("Exception_SyncDatabase", e.ToString()); } } } ); Action syncService = new Action(() => { foreach (Data d in ChangedDataService) { try { // ... // analyzing & syncing } catch (Exception e) { logger.InfoEx("Exception_SyncService", e.ToString()); } } }); List<WaitHandle> handles = new List<WaitHandle>(); IAsyncResult ar1 = syncDBChanges.BeginInvoke(syncDBChanges.EndInvoke, null); IAsyncResult ar2 = syncService.BeginInvoke(syncService.EndInvoke, null); handles.Add(ar1.AsyncWaitHandle); handles.Add(ar2.AsyncWaitHandle); WaitHandle.WaitAll(handles.ToArray(), (int)((Global.config.syncModifiedInterval - 1) * 1000)); SetCurrentIterationTS(l.id); } catch (Exception e) { Console.WriteLine(e.Message); logger.InfoEx("Exception_Iteration", e.ToString()); continue; } } logger.InfoEx("end_Iteration", IterationContextParams); } ); s1.Stop(); Console.WriteLine("Main iteration done for {0}...", s1.Elapsed);
kseen
source share