How can I properly unsubscribe to an event and be sure that the called method is not called now ?
My problem is with this kind of code :
public class MyClassWithEvent
{
public event EventHandler MyEvent;
public int Field;
}
public class MyMainClass
{
private MyClassWithEvent myClass;
public void Start()
{
myClass.MyEvent += new EventHandler(doSomething);
}
public void Stop()
{
myClass.MyEvent -= new EventHandler(doSomething);
myClass = null;
}
private void doSomething()
{
myClass.Field = 42;
}
}
If myClass = null is called while doSomething is executing, instruction myClass.Field = 42 raise an error because myClass is null.
How can I be sure that doSomething is not executing before setting myClass = null ?
Edit:
Other example:
public void Stop()
{
myClass.MyEvent -= new EventHandler(doSomething);
// Can I add a function here to be sure that doSomething is not running ?
myClass.Field = 101;
}
In that case, I will not be sure if myClass.Field is 42 or 101.
Edit2:
Apparently my question is not as simple as I thought. I will explain my precise case.
My code is :
public class MyMainClass
{
object camera;//can be type uEye.Camera or DirectShowCamera
bool isRunning = false;
public void Start()
{
if (camera is uEye.Camera)
{
camera.EventFrame += new EventHandler(NewFrameArrived);
}
else if (camera is DirectShowCamera)
{
//other init
}
isRunning = true;
}
public void Stop()
{
if (camera is uEye.Camera)
{
camera.EventFrame -= new EventHandler(NewFrameArrived);
camera.exit;
}
else if (camera is DirectShowCamera)
{
//other stop
}
isRunning = false;
}
public void ChangeCamera(object new camera)
{
if (isRunning)
Stop()
camera = new camera();
}
void NewFrameArrived(object sender, EventArgs e)
{
uEye.Camera Camera = sender as uEye.Camera;
Int32 s32MemID;
Camera.Memory.GetActive(out s32MemID);
lock (_frameCameralocker)
{
if (_frameCamera != null)
_frameCamera.Dispose();
_frameCamera = null;
Camera.Memory.ToBitmap(s32MemID, out _frameCamera);
}
Dispatcher.Invoke(new Action(() =>
{
lock (_frameCameralocker)
{
var bitmapData = _frameCamera.LockBits(
new System.Drawing.Rectangle(0, 0, _frameCamera.Width, _frameCamera.Height),
System.Drawing.Imaging.ImageLockMode.ReadOnly, _frameCamera.PixelFormat);
if (_frameCamera.PixelFormat == System.Drawing.Imaging.PixelFormat.Format8bppIndexed)
{
DeviceSource = System.Windows.Media.Imaging.BitmapSource.Create(
bitmapData.Width, bitmapData.Height, 96, 96, System.Windows.Media.PixelFormats.Gray8, null,
bitmapData.Scan0, bitmapData.Stride * bitmapData.Height, bitmapData.Stride);
}
_frameCamera.UnlockBits(bitmapData);
if (OnNewBitmapReady != null)
OnNewBitmapReady(this, null);
}
}));
}
}
And when I change the camera from uEye to directshow sometime I have a AccessViolationException in DeviceSource = System.Windows.Media.Imaging.BitmapSource.Create (method NewFrameArrived) because I try to create BitmapSource from an exited camera
From your updated question, the only thing you need to do is just lock the Stop() action from the same lock as the Dispatcher.Invoke
public void Stop()
{
lock(_frameCameralocker)
{
if (camera is uEye.Camera)
{
camera.EventFrame -= new EventHandler(NewFrameArrived);
camera.exit;
}
else if (camera is DirectShowCamera)
{
//other stop
}
isRunning = false;
}
}
This will make sure all NewFrameArrived calls finished or have not started before you create the new camera. Then inside the dispatcher check to see if you are running or not just in case a frame was queued before a Stop() call was started and completed.
Dispatcher.Invoke(new Action(() =>
{
lock (_frameCameralocker)
{
if(!isRunning)
return;
var bitmapData = _frameCamera.LockBits(
new System.Drawing.Rectangle(0, 0, _frameCamera.Width, _frameCamera.Height),
System.Drawing.Imaging.ImageLockMode.ReadOnly, _frameCamera.PixelFormat);
if (_frameCamera.PixelFormat == System.Drawing.Imaging.PixelFormat.Format8bppIndexed)
{
DeviceSource = System.Windows.Media.Imaging.BitmapSource.Create(
bitmapData.Width, bitmapData.Height, 96, 96, System.Windows.Media.PixelFormats.Gray8, null,
bitmapData.Scan0, bitmapData.Stride * bitmapData.Height, bitmapData.Stride);
}
_frameCamera.UnlockBits(bitmapData);
if (OnNewBitmapReady != null)
OnNewBitmapReady(this, null);
}
}));
Maybe a good use for Monitor ?
The idea is that you use a lock to make sure you are not using the same resource twice at the (almost) same time :
public class MyClassWithEvent
{
public event EventHandler MyEvent;
public int Field;
}
public class MyMainClass
{
private MyClassWithEvent myClass;
private object mylock;
public void Start()
{
myClass.MyEvent += new EventHandler(doSomething);
}
public void Stop()
{
myClass.MyEvent -= new EventHandler(doSomething);
Monitor.Enter(mylock); //If somebody else already took the lock, we will wait here
myClass = null;
Monitor.Exit(mylock); //We release the lock, so others can access it
}
private void doSomething()
{
Monitor.Enter(mylock);
if myClass != null
{
myClass.Field = 42;
}
Monitor.Exit(mylock);
}
}
EDIT
According to comments, Lock would be a better use (actually a short-hand for Monitor) :
public class MyClassWithEvent
{
public event EventHandler MyEvent;
public int Field;
}
public class MyMainClass
{
private MyClassWithEvent myClass;
private object mylock;
public void Start()
{
myClass.MyEvent += new EventHandler(doSomething);
}
public void Stop()
{
myClass.MyEvent -= new EventHandler(doSomething);
lock (mylock) //If somebody else already took the lock, we will wait here
{
myClass = null;
} //We release the lock, so others can access it
}
private void doSomething()
{
lock(mylock)
{
if myClass != null
{
myClass.Field = 42;
}
}
}
}
Instead
myClass.Field = 42;
Do
val local = myClass;
if (local != null)
local.Field = 42;
Related
I'm trying to build a system via which users can build a little test program without knowing how to code. For that purpose I designed the system that way, that there is a procedure, which can contain other procedures or steps. The steps can contain commands. The procedure contains the logic what happens in which order. The steps contain the information to which step they are connected next.
The steps and commands are called by Execute and invoke OnDone if they are finished which may happen directly (eg IncreaseCommand) or after a certain period of time (WaitCommand or any other command communicating with the connected hardware; both are on a different thread). Additionally they can be stopped by a timeout or by user.
As long as there is no timeout everything works fine. If there is a timeout I tried to make the code thread safe by locking. Additionally there are these pitfalls when the timeout stops a command (eg WaitCommand) which is finishing its work in the same moment. So there is one thread working its way from the procedure via the step to the command, signalling stop and another thread working from the command via the step to the procedure signalling done.
I added some code snippets, which I've stripped of most of the dispose code and other internal stuff, which seems not to be related to the issue.
public sealed class Procedure : IStep, IStoppable
{
public event EventHandler Done;
public event EventHandler Stopped;
public event EventHandler TimedOut;
public void Run()
{
if (!IsRunning)
{
CheckStartTimer();
Start(First);
}
}
private void CheckStartTimer()
{
isTimerUnlinked = false;
timer.Elapsed += OnTimedOut;
timer.IntervalInMilliseconds = (int)Timeout.TotalMilliseconds;
timer.Start();
}
private void OnTimedOut(object sender, EventArgs e)
{
if (isTimerUnlinked)
return;
stopFromTimeout = true;
Stop();
}
private void Start(IStep step)
{
isStopped = false;
isStopping = false;
Active = step;
LinkActive();
active.Run();
}
private void LinkActive()
{
active.Done += OnActiveFinished;
if (active is Procedure proc)
proc.TimedOut += OnActiveFinished;
}
private void OnActiveFinished(object sender, EventArgs e)
{
UnlinkActive();
lock (myLock)
{
if (isStopped)
return;
if (stopFromTimeout)
{
OnStopped();
return;
}
}
var successor = active.ActiveSuccessor;
if (successor == null)
OnDone();
else if (isStopping || timeoutPending || stopFromTimeout)
OnStopped();
else
Start(successor);
}
public void Stop()
{
if (isStopping)
return;
isStopping = true;
StopTimer();
if (active is IStoppable stoppable)
{
stoppable.Stopped += stoppable_Stopped;
stoppable.Stop();
}
else
OnStopped();
}
private void stoppable_Stopped(object sender, EventArgs e)
{
var stoppable = sender as IStoppable;
stoppable.Stopped -= stoppable_Stopped;
OnStopped();
}
private void OnStopped()
{
isStopping = false;
lock (myLock)
{
isStopped = true;
}
UnlinkActive();
lock (myLock)
{
Active = null;
}
if (stopFromTimeout || timeoutPending)
{
stopFromTimeout = false;
timeoutPending = false;
CleanUp();
TimedOut?.Invoke(this, EventArgs.Empty);
}
else
Stopped?.Invoke(this, EventArgs.Empty);
}
private void UnlinkActive()
{
if (stopFromTimeout && !isStopped)
return;
lock (myLock)
{
if (active == null)
return;
active.Done -= OnActiveFinished;
var step = active as IStep;
if (step is Procedure proc)
proc.TimedOut -= OnActiveFinished;
}
}
private void OnDone()
{
CleanUp();
Done?.Invoke(this, EventArgs.Empty);
}
private void CleanUp()
{
Reset();
SetActiveSuccessor();
}
private void Reset()
{
Active = null;
stopFromTimeout = false;
timeoutPending = false;
StopTimer();
}
private void StopTimer()
{
if (timer == null)
return;
isTimerUnlinked = true;
timer.Elapsed -= OnTimedOut;
timer.Stop();
}
private void SetActiveSuccessor()
{
ActiveSuccessor = links[(int)Successor.Simple_If];
}
}
internal sealed class CommandStep : IStep, IStoppable
{
public event EventHandler Done;
public event EventHandler Started;
public event EventHandler Stopped;
public CommandStep(ICommand command)
{
this.command = command;
}
public void Run()
{
lock (myLock)
{
stopCalled = false;
if (cookie != null && !cookie.Signalled)
throw new InvalidOperationException(ToString() + " is already active.");
cookie = new CommandStepCookie();
}
command.Done += OnExit;
unlinked = false;
if (stopCalled)
return;
command.Execute();
}
public void Stop()
{
stopCalled = true;
if (command is IStoppable stoppable)
stoppable.Stop();
else
OnExit(null, new CommandEventArgs(ExitReason.Stopped));
}
private void OnExit(object sender, CommandEventArgs e)
{
(sender as ICommand).Done -= OnExit;
lock (myLock)
{
if (cookie.Signalled)
return;
cookie.ExitReason = stopCalled ? ExitReason.Stopped : e.ExitReason;
switch (cookie.ExitReason)
{
case ExitReason.Done:
default:
if (unlinked)
return;
Unlink();
ActiveSuccessor = links[(int)Successor.Simple_If];
break;
case ExitReason.Stopped:
Unlink();
break;
case ExitReason.Error:
throw new NotImplementedException();
}
cookie.Signalled = true;
}
if (cookie.ExitReason.HasValue)
{
active = false;
if (cookie.ExitReason == ExitReason.Done)
Done?.Invoke(this, EventArgs.Empty);
else if (cookie.ExitReason == ExitReason.Stopped)
stopCalled = false;
Stopped?.Invoke(this, EventArgs.Empty);
}
}
private void Unlink()
{
if (command != null)
command.Done -= OnExit;
unlinked = true;
}
}
internal sealed class WaitCommand : ICommand, IStoppable
{
public event EventHandler<CommandEventArgs> Done;
public event EventHandler Stopped;
internal WaitCommand(ITimer timer)
{
this.timer = timer;
timer.AutoRestart = false;
TimeSpan = TimeSpan.FromMinutes(1);
}
public void Execute()
{
lock (myLock)
{
cookie = new WaitCommandCookie(
e => Done?.Invoke(this, new CommandEventArgs(e)));
timer.IntervalInMilliseconds = (int)TimeSpan.TotalMilliseconds;
timer.Elapsed += OnElapsed;
}
timer.Start();
}
private void OnElapsed(object sender, EventArgs e)
{
OnExit(ExitReason.Done);
}
public void Stop()
{
if (cookie == null)
{
Done?.Invoke(this, new CommandEventArgs(ExitReason.Stopped));
return;
}
cookie.Stopping = true;
lock (myLock)
{
StopTimer();
}
OnExit(ExitReason.Stopped);
}
private void OnExit(ExitReason exitReason)
{
if (cookie == null)
return;
lock (myLock)
{
if (cookie.Signalled)
return;
Unlink();
if (cookie.Stopping && exitReason != ExitReason.Stopped)
return;
cookie.Stopping = false;
}
cookie.Signal(exitReason);
cookie = null;
}
private void StopTimer()
{
Unlink();
timer.Stop();
}
private void Unlink()
{
timer.Elapsed -= OnElapsed;
}
}
I've been testing at certain places whether a stop is ongoing and trying to intercept the done, so that it is not executed after the stop and cause any trouble. This way doesn't seem to be fully waterproof, althoug it seems to work for the moment. Is there a way to provide this kind of safety by design? Am I maybe doing this completely wrong?
Your shared state is not protected from concurrent access consistently. For example take the isStopped field:
private void OnStopped()
{
isStopping = false;
lock (myLock)
{
isStopped = true;
}
//...
private void Start(IStep step)
{
isStopped = false;
//...
In the first place it's protected, in the second it's not. You can either choose to protect it everywhere, or nowhere. There is no middle ground. Protecting it partially is as good as not protecting it at all.
As a side note, invoking event handlers while holding a lock is not recommended. An event handler could contain long running code, or call arbitrary code that is possibly protected by other locks, opening the possibility for deadlocks. The general advice about locking is to release it as quickly as possible. The longer you hold a lock, the more contention you create between threads. So for example in the method OnActiveFinished:
lock (myLock)
{
if (isStopped)
return;
if (stopFromTimeout)
{
OnStopped();
return;
}
}
You call the OnStopped while holding the lock. And inside the OnStopped you invoke the handlers:
Stopped?.Invoke(this, EventArgs.Empty);
The correct way is to call the OnStopped after releasing the lock. Use a local variable for storing the info about calling it or not:
var localInvokeOnStopped = false;
lock (myLock)
{
if (isStopped)
return;
if (stopFromTimeout)
{
localInvokeOnStopped = true;
}
}
if (localInvokeOnStopped)
{
OnStopped();
return;
}
Last advice, avoid locking recursively on the same lock. The lock statement will not complain if you do it (because the underlying Monitor class allows reentrancy), but it makes your program less understandable and maintainable.
This question already has answers here:
Use Unity API from another Thread or call a function in the main Thread
(5 answers)
Closed 6 years ago.
I'm having trouble with a UnityEngine version. (Can't upgrade, game is not mine)
The server RANDOMLY crashes when a specific UnityEngine method is used in a timer/thread (It was fixed in a version, I read It)
It happens totally random, I get a crash log, that starts from the timer/thread and ends at a UnityEngine method. (This never happens when I use It in the main thread)
My question is that Is It possible somehow to call the method from the main thread if the current thread != with the main thread?
Any help is appreciated
This Loom class is able to call the specific method from the Main thread, this is how you do It:
public class Loom : MonoBehaviour
{
public static int maxThreads = 10;
static int numThreads;
private static Loom _current;
private int _count;
public static Loom Current
{
get
{
Initialize();
return _current;
}
}
public void Awake()
{
_current = this;
initialized = true;
}
static bool initialized;
static void Initialize()
{
if (!initialized)
{
if (!Application.isPlaying)
return;
initialized = true;
var g = new GameObject("Loom");
_current = g.AddComponent<Loom>();
}
}
private List<Action> _actions = new List<Action>();
public struct DelayedQueueItem
{
public float time;
public Action action;
}
private List<DelayedQueueItem> _delayed = new List<DelayedQueueItem>();
List<DelayedQueueItem> _currentDelayed = new List<DelayedQueueItem>();
public static void QueueOnMainThread(Action action)
{
QueueOnMainThread(action, 0f);
}
public static void QueueOnMainThread(Action action, float time)
{
if (time != 0)
{
lock (Current._delayed)
{
Current._delayed.Add(new DelayedQueueItem { time = Time.time + time, action = action });
}
}
else
{
lock (Current._actions)
{
Current._actions.Add(action);
}
}
}
public static Thread RunAsync(Action a)
{
Initialize();
while (numThreads >= maxThreads)
{
Thread.Sleep(1);
}
Interlocked.Increment(ref numThreads);
ThreadPool.QueueUserWorkItem(RunAction, a);
return null;
}
private static void RunAction(object action)
{
try
{
((Action)action)();
}
catch
{
}
finally
{
Interlocked.Decrement(ref numThreads);
}
}
public void OnDisable()
{
if (_current == this)
{
_current = null;
}
}
// Use this for initialization
public void Start()
{
}
List<Action> _currentActions = new List<Action>();
// Update is called once per frame
public void Update()
{
lock (_actions)
{
_currentActions.Clear();
_currentActions.AddRange(_actions);
_actions.Clear();
}
foreach (var a in _currentActions)
{
a();
}
lock (_delayed)
{
_currentDelayed.Clear();
_currentDelayed.AddRange(_delayed.Where(d => d.time <= Time.time));
foreach (var item in _currentDelayed)
_delayed.Remove(item);
}
foreach (var delayed in _currentDelayed)
{
delayed.action();
}
}
}
//Usage
public void Call()
{
if (Thread.CurrentThread.ManagedThreadId != TestClass.MainThread.ManagedThreadId)
{
Loom.QueueOnMainThread(() => {
Call();
});
return;
}
Console.WriteLine("Hello");
}
Desription:
I am adding some data to list every second. After every 10 seconds, the data is saved to the database and then I clear the list. If I stop the timer, I am saving the data remaining in the list and then clearing the list and then stopping the timer.
In the above code, Let's say when I stop the timer after 11 seconds, The Class1s list should have only 1 data, but I see there are 11 datas. Can you guys tell what I am doing wrong here? Maybe my use of lock is incorrect or my code is totally incorrect
public class Class1Singleton
{
private static Class1Singleton Class1Singleton;
private static List<Class1> Class1s;
private static Timer saveClass1Timer;
private static readonly object lock1 = new object();
private Class1Singleton()
{
}
public static Class1Singleton getInstance()
{
if (Class1Singleton == null) {
try
{
Class1Singleton = new Class1Singleton();
}
catch (Exception e){}
}
return Class1Singleton;
}
public void StartTimer()
{
if (saveClass1Timer == null)
{
saveClass1Timer = new Timer(10000);
//saveClass1Timer.Interval = 10000;
saveClass1Timer.Elapsed += new ElapsedEventHandler(SaveClass1);
saveClass1Timer.Enabled = true;
}
}
public void SaveClass1(object sender, ElapsedEventArgs e)
{
try {
lock (lock1)
{
new Class1Repository().InsertAllClass1(Class1s);
ClearWorkoutList();
}
}
catch (Exception ex){}
}
public void InsertClass1(List<Class1> Class1)
{
if (Class1s == null)
{
Class1s = new List<Class1>(Class1);
}
else
{
lock (lock1)
{
Class1s.AddRange(Class1);
}
}
}
public void ClearWorkoutList()
{
if (Class1s != null)
{
Class1s.Clear();
}
}
public void StopTimer()
{
if (Class1s != null && Class1s.Count > 0)
{
lock (lock1)
{
new Class1Repository().InsertAllClass1(Class1s);
ClearWorkoutList();
}
}
if (saveClass1Timer != null && saveClass1Timer.Enabled == true)
{
saveClass1Timer.Stop();
}
}
}
I've made a few changes to your code (see comments):
public class Class1Singleton
{
// This is the way Jon Skeet recommends implementing a singleton in C#
// See http://csharpindepth.com/Articles/General/Singleton.aspx
static readonly Class1Singleton instance = new Class1Singleton();
// Explicit static constructor to tell C# compiler
// not to mark type as beforefieldinit
static Class1Singleton() { }
// There's only one instance of Class1Singleton so there's
// no advantage in making the members static
private List<Class1> Class1s;
private Timer saveClass1Timer;
private readonly object lock1 = new object();
Class1Singleton()
{
}
public static Class1Singleton Instance
{
get { return instance; }
}
public void StartTimer()
{
// If you're using this class in a multi-thread environment,
// all methods that access the list or timer should be locked
lock (lock1)
{
if (saveClass1Timer == null)
{
saveClass1Timer = new Timer(10000);
//saveClass1Timer.Interval = 10000;
saveClass1Timer.Elapsed += new ElapsedEventHandler(SaveClass1);
saveClass1Timer.Enabled = true;
}
}
}
// SaveClass1 doesn't need to be public
private void SaveClass1(object sender, ElapsedEventArgs e)
{
lock (lock1)
{
SaveWorkoutList();
ClearWorkoutList();
}
}
private void SaveWorkoutList()
{
//new Class1Repository().InsertAllClass1(Class1s);
}
public void InsertClass1(List<Class1> Class1)
{
lock (lock1)
{
if (Class1s == null)
Class1s = new List<Class1>(Class1);
else
Class1s.AddRange(Class1);
}
}
private void ClearWorkoutList()
{
if (Class1s != null)
{
Class1s.Clear();
}
}
public void StopTimer()
{
lock (lock1)
{
if (Class1s != null && Class1s.Count > 0)
{
SaveWorkoutList();
ClearWorkoutList();
}
if (saveClass1Timer != null && saveClass1Timer.Enabled == true)
{
saveClass1Timer.Stop();
}
}
}
}
I am trying to fire the event handler assigned to my timer mock. How can I test this private method here?
public interface ITimer
{
void Start();
double Interval { get; set; }
event ElapsedEventHandler Elapsed;
}
Client class assigns an event handler to this object. I want to test the logic in this class.
_timer.Elapsed += ResetExpiredCounters;
And the assigned method is private
private void ResetExpiredCounters(object sender, ElapsedEventArgs e)
{
// do something
}
I want to have this event handler in my mock and run it somehow. How can I do this?
Update:
I realized I was raising the event before I assigned the event handler. I corrected that but I still get this error:
System.ArgumentException : Object of type 'System.EventArgs' cannot be converted
to type 'System.Timers.ElapsedEventArgs'.
I raise it like this:
_timer.Raise(item => item.Elapsed += null, ElapsedEventArgs.Empty);
or
_timer.Raise(item => item.Elapsed += null, EventArgs.Empty);
Both won't work.
Update:
Here's the thing that worked for me. Note that it's not useful if you are trying to pass info to event handler like Jon pointed out in comments. I am just using it to mock the wrapper for System.Timers.Timer class.
_timer.Raise(item => item.Elapsed += null, new EventArgs() as ElapsedEventArgs);
In the end, this won't help at all if you need to use event arguments since it will be always null. However, it's the only way since ElapsedEventArgs has only an internal constructor.
ElapsedEventArgs has a private constructor and can not be instantiated.
If you use:
timer.Raise(item => item.Elapsed += null, new EventArgs() as ElapsedEventArgs);
Then the handler will recevie a null parameter and lose its SignalTime property:
private void WhenTimerElapsed(object sender, ElapsedEventArgs e)
{
// e is null.
}
You might want this parameter in some cases.
To solve this and make it more testable, I also created a wrapper for the ElapsedEventArgs, and made the interface use it:
public class TimeElapsedEventArgs : EventArgs
{
public DateTime SignalTime { get; private set; }
public TimeElapsedEventArgs() : this(DateTime.Now)
{
}
public TimeElapsedEventArgs(DateTime signalTime)
{
this.SignalTime = signalTime;
}
}
public interface IGenericTimer : IDisposable
{
double IntervalInMilliseconds { get; set; }
event EventHandler<TimerElapsedEventArgs> Elapsed;
void StartTimer();
void StopTimer();
}
The implementation will simply fire its own event getting the data from the real timer event:
public class TimerWrapper : IGenericTimer
{
private readonly System.Timers.Timer timer;
public event EventHandler<TimerElapsedEventArgs> Elapsed;
public TimeSpan Interval
{
get
{
return this.timer.Interval;
}
set
{
this.timer.Interval = value;
}
}
public TimerWrapper (TimeSpan interval)
{
this.timer = new System.Timers.Timer(interval.TotalMilliseconds) { Enabled = false };
this.timer.Elapsed += this.WhenTimerElapsed;
}
private void WhenTimerElapsed(object sender, ElapsedEventArgs elapsedEventArgs)
{
var handler = this.Elapsed;
if (handler != null)
{
handler(this, new TimeElapsedEventArgs(elapsedEventArgs.SignalTime));
}
}
public void StartTimer()
{
this.timer.Start();
}
public void StopTimer()
{
this.timer.Stop();
}
public void Dispose()
{
this.Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (!this.disposed)
{
if (disposing)
{
this.timer.Elapsed -= this.WhenTimerElapsed;
this.timer.Dispose();
}
this.disposed = true;
}
}
}
Now, you can simplify and improve the mock of this event:
timer.Raise(item => item.Elapsed += null, new TimeElapsedEventArgs());
var yesterday = DateTime.Now.AddDays(-1);
timer.Raise(item => item.Elapsed += null, new TimeElapsedEventArgs(yesterday));
Less code to write, easier to work with and completely decoupled from the framework.
The Moq QuickStart guide has a section on events. I think you'd use
mock.Raise(m => m.Elapsed += null, new ElapsedEventArgs(...));
Dealt with this recently, you can construct an ElapsedEventArgs using reflection:
public ElapsedEventArgs CreateElapsedEventArgs(DateTime signalTime)
{
var e = FormatterServices.GetUninitializedObject(typeof(ElapsedEventArgs)) as ElapsedEventArgs;
if (e != null)
{
var fieldInfo = e.GetType().GetField("signalTime", BindingFlags.NonPublic | BindingFlags.Instance);
if (fieldInfo != null)
{
fieldInfo.SetValue(e, signalTime);
}
}
return e;
}
This way you can continue using the original ElapsedEventHandler delegate
var yesterday = DateTime.Now.AddDays(-1);
timer.Raise(item => item.Elapsed += null, CreateElapsedEventArgs(yesterday));
Could do something like this to wrap your Timer
public class FakeTimer : IMyTimer
{
private event ElapsedEventHandler elaspedHandler;
private bool _enabled;
public void Dispose() => throw new NotImplementedException();
public FakeTimer(ElapsedEventHandler elapsedHandlerWhenTimeFinished, bool startImmediately)
{
this.elaspedHandler = elapsedHandlerWhenTimeFinished;
_enabled = startImmediately;
}
public void Start() => _enabled = true;
public void Stop() => _enabled = false;
public void Reset() => _enabled = true;
internal void TimeElapsed()
{
if (this._enabled)
elaspedHandler.Invoke(this, new EventArgs() as ElapsedEventArgs);
}
}
copy paste the following code in new C# console app.
class Program
{
static void Main(string[] args)
{
var enumerator = new QueuedEnumerator<long>();
var listenerWaitHandle = Listener(enumerator);
Publisher(enumerator);
listenerWaitHandle.WaitOne();
}
private static AutoResetEvent Listener(IEnumerator<long> items)
{
var #event = new AutoResetEvent(false);
ThreadPool.QueueUserWorkItem((o) =>
{
while (items.MoveNext())
{
Console.WriteLine("Received : " + items.Current);
Thread.Sleep(2 * 1000);
}
(o as AutoResetEvent).Set();
}, #event);
return #event;
}
private static void Publisher(QueuedEnumerator<long> enumerator)
{
for (int i = 0; i < 10; i++)
{
enumerator.Set(i);
Console.WriteLine("Sended : " + i);
Thread.Sleep(1 * 1000);
}
enumerator.Finish();
}
class QueuedEnumerator<T> : IEnumerator<T>
{
private Queue _internal = Queue.Synchronized(new Queue());
private T _current;
private bool _finished;
private AutoResetEvent _setted = new AutoResetEvent(false);
public void Finish()
{
_finished = true;
_setted.Set();
}
public void Set(T item)
{
if (_internal.Count > 3)
{
Console.WriteLine("I'm full, give the listener some slack !");
Thread.Sleep(3 * 1000);
Set(item);
}
else
{
_internal.Enqueue(item);
_setted.Set();
}
}
public T Current
{
get { return _current; }
}
public void Dispose()
{
}
object System.Collections.IEnumerator.Current
{
get { return _current; }
}
public bool MoveNext()
{
if (_finished && _internal.Count == 0)
return false;
else if (_internal.Count > 0)
{
_current = (T)_internal.Dequeue();
return true;
}
else
{
_setted.WaitOne();
return MoveNext();
}
}
public void Reset()
{
}
}
}
2 threads (A,B)
A thread can provide one instance at a time and calls the Set method
B thread wants to receive a sequence of instances (provided by thread A)
So literally transforming an Add(item), Add(item), .. to a IEnumerable between different threads
Other solutions also welcome of course!
Sure - this code might not be the best way to do it, but here was my initial stab at it:
Subject<Item> toAddObservable;
ListObservable<Item> buffer;
void Init()
{
// Subjects are an IObservable we can trigger by-hand, they're the
// mutable variables of Rx
toAddObservable = new Subject(Scheduler.TaskPool);
// ListObservable will hold all our items until someone asks for them
// It will yield exactly *one* item, but only when toAddObservable
// is completed.
buffer = new ListObservable<Item>(toAddObservable);
}
void Add(Item to_add)
{
lock (this) {
// Subjects themselves are thread-safe, but we still need the lock
// to protect against the reset in FetchResults
ToAddOnAnotherThread.OnNext(to_add);
}
}
IEnumerable<Item> FetchResults()
{
IEnumerable<Item> ret = null;
buffer.Subscribe(x => ret = x);
lock (this) {
toAddObservable.OnCompleted();
Init(); // Recreate everything
}
return ret;
}