Putting the test thread to sleep prevents the asynchronous events from happening (it’s on the same thread as the SharePoint code) and, even though your code is working when you are executing it manually, all of the tests fail so I have created a new class based on timers that will let the asynchronous events to trigger and execute. I call it Waiter.
public class Waiter : IDisposable { public enum WaiterState { Waiting, TimedOut, Success, Error }; System.Timers.Timer WaitTimer; ManualResetEvent manualResetEvent; int WaitCounter; private Waiter(int interval) { WaitCounter = 0; manualResetEvent = new ManualResetEvent(true); WaitTimer = new System.Timers.Timer() { AutoReset = false, Interval = interval }; WaitTimer.Elapsed += new ElapsedEventHandler(WaitTimer_Elapsed); } void WaitTimer_Elapsed(object sender, ElapsedEventArgs e) { WaitCounter++; manualResetEvent.Set(); } ///Give it a go./// Waits for the interval in milliseconds times number of times or once by default. /// public static WaiterState Wait(int interval, int times) { try { using (Waiter WaiterClass = new Waiter(interval)) { while (WaiterClass.WaitCounter <= times) { WaiterClass.WaitTimer.Start(); WaiterClass.manualResetEvent.WaitOne(); } } } catch { return WaiterState.Error; } return WaiterState.Success; } ////// Waits for the interval in milliseconds once. /// public static WaiterState Wait(int interval) { return Wait(interval, 0); } void Dispose() { WaitTimer.Dispose(); } }
No comments:
Post a Comment