Reputation: 341
I had checked out Timer in Portable Library, but I had no idea how to call the Change function, because it was not implemented in the class nor inherited from parent.
_timer = new Timer(OnTimerTick, null, TimeSpan.FromSeconds(1.0), TimeSpan.Zero);
_timer.Change(TimeSpan.FromSeconds(1.0), TimeSpan.Zero); //how to implement this
Upvotes: 1
Views: 301
Reputation: 15981
I have developed a support library containing types missing or incomplete in PCL. The library is called Shim and is also available on NuGet.
Shim comes in different instances for different platform targets. If you install Shim form NuGet, it will pick the relevant instance for your Visual Studio project, be it a portable class library, a Windows 8 application or a Xamarin.Android class library.
Shim contains a declaration of System.Threading.Timer
, including two constructors and the Change(int, int)
method. When using Shim from a Windows 8 application or class library, there is a Windows 8 specific implementation using the Windows.System.Threading.ThreadPoolTimer
class internally. For the other (non-PCL) platform targets a [TypeForwardedTo]
declaration is used to forward calls to the existing implementation for this particular target.
Some general implementation details can be found in this SO answer. If you don't want the overhead of the full Shim package, you could use the approach presented in this SO answer to implement the necessary parts yourself.
Upvotes: 1
Reputation: 341
Instead of using the 1st solution: (building the class Timer) by David Kean, I am now using his 3rd solution: (create a target .NET 4.0 Timer adapter) with the code sample by Henry C.
Anyway, I'm still hoping to get some feedback on how to implement the Change function in the Timer class as defined in .NET. Thanks!
public class PCLTimer
{
private System.Threading.Timer timer;
private Action<object> action;
public PCLTimer(Action<object> action, object state, int dueTimeMilliseconds, int periodMilliseconds)
{
this.action = action;
timer = new System.Threading.Timer(PCLTimerCallback, state, dueTimeMilliseconds, periodMilliseconds);
}
public PCLTimer(Action<object> action, object state, TimeSpan dueTimeMilliseconds, TimeSpan periodMilliseconds)
{
this.action = action;
timer = new System.Threading.Timer(PCLTimerCallback, state, dueTimeMilliseconds, periodMilliseconds);
}
private void PCLTimerCallback(object state)
{
action.Invoke(state);
}
public bool Change(int dueTimeMilliseconds, int periodMilliseconds)
{
return timer.Change(dueTimeMilliseconds, periodMilliseconds);
}
public bool Change(TimeSpan dueTimeMilliseconds, TimeSpan periodMilliseconds)
{
return timer.Change(dueTimeMilliseconds, periodMilliseconds);
}
public new void Dispose()
{
timer.Dispose();
}
}
Upvotes: 1