public WaitForChangedResult WaitForChanged(WatcherChangeTypes changeType, int timeout)
{
// The full framework implementation doesn't do any argument validation, so
// none is done here, either.
var tcs = new TaskCompletionSource<WaitForChangedResult>();
FileSystemEventHandler fseh = null;
RenamedEventHandler reh = null;
// Register the event handlers based on what events are desired. The full framework
// doesn't register for the Error event, so this doesn't either.
if ((changeType & (WatcherChangeTypes.Created | WatcherChangeTypes.Deleted | WatcherChangeTypes.Changed)) != 0)
{
fseh = (s, e) =>
{
if ((e.ChangeType & changeType) != 0)
{
tcs.TrySetResult(new WaitForChangedResult(e.ChangeType, e.Name, oldName: null, timedOut: false));
}
};
if ((changeType & WatcherChangeTypes.Created) != 0) Created += fseh;
if ((changeType & WatcherChangeTypes.Deleted) != 0) Deleted += fseh;
if ((changeType & WatcherChangeTypes.Changed) != 0) Changed += fseh;
}
if ((changeType & WatcherChangeTypes.Renamed) != 0)
{
reh = (s, e) =>
{
if ((e.ChangeType & changeType) != 0)
{
tcs.TrySetResult(new WaitForChangedResult(e.ChangeType, e.Name, e.OldName, timedOut: false));
}
};
Renamed += reh;
}
try
{
// Enable the FSW if it wasn't already.
bool wasEnabled = EnableRaisingEvents;
if (!wasEnabled)
{
EnableRaisingEvents = true;
}
// Block until an appropriate event arrives or until we timeout.
Debug.Assert(EnableRaisingEvents, "Expected EnableRaisingEvents to be true");
tcs.Task.Wait(timeout);
// Reset the enabled state to what it was.
EnableRaisingEvents = wasEnabled;
}
finally
{
// Unregister the event handlers.
if (reh != null)
{
Renamed -= reh;
}
if (fseh != null)
{
if ((changeType & WatcherChangeTypes.Changed) != 0) Changed -= fseh;
if ((changeType & WatcherChangeTypes.Deleted) != 0) Deleted -= fseh;
if ((changeType & WatcherChangeTypes.Created) != 0) Created -= fseh;
}
}
// Return the results.
return tcs.Task.Status == TaskStatus.RanToCompletion ?
tcs.Task.Result :
WaitForChangedResult.TimedOutResult;
}