Forum Xamarin Xamarin.Forms

Timer doesn't contain in System.Threading

I used System.Threading.Timer in Xamarin.Android.

How I can use the same class in Xamarin.Forms?
(I want to transfer my project from Xamarin.Android in Xamarin.Forms)

Tagged:

Best Answers

Answers

  • KirillRadchenkoKirillRadchenko RUMember ✭✭
    edited August 2015

    How I can write this code (using Device.StartTimer) ?

    public static System.Threading.Timer timer;
    if (timer == null)
    {
        System.Threading.TimerCallback tcb = MyMethod;
        timer = new System.Threading.Timer(tcb, null, 700, System.Threading.Timeout.Infinite);
    }
    else
    {
        timer.Change(System.Threading.Timeout.Infinite, System.Threading.Timeout.Infinite);
        timer.Change(700, System.Threading.Timeout.Infinite);
    }
    
  • AlessandroCaliaroAlessandroCaliaro ITMember ✭✭✭✭✭

    If I remember correctly there is a plugin...I don't remember the name. Try to search in Xamarin plugin

  • KirillRadchenkoKirillRadchenko RUMember ✭✭

    Thank you very much!
    But your internal sealed class Timer doesn't contain method Change:

    timer.Change(System.Threading.Timeout.Infinite, System.Threading.Timeout.Infinite);
    timer.Change(700, System.Threading.Timeout.Infinite);
    

    I need to stop my timer and start this timer again.

  • KirillRadchenkoKirillRadchenko RUMember ✭✭

    Sorry, this code

    timer.Change(System.Threading.Timeout.Infinite, System.Threading.Timeout.Infinite);
    timer.Change(700, System.Threading.Timeout.Infinite);
    

    is equal

    timer.Dispose ();
    timer = new Timer("", tcb, null, 700, System.Threading.Timeout.Infinite);
    

    Thanks for the help, Christian.

  • ChristianFalchChristianFalch NODeveloper Group Leader ✭✭✭

    No problem, @KirillRadchenko :smile:

  • adamkempadamkemp USInsider, Developer Group Leader mod

    System.Threading.Timer is an API no one should use ever. It's very difficult to use correctly if you ever need to stop it, and very few people manage to get it right. Always use a timer tied to a dispatcher of some sort. Device.StartTimer works for Forms projects. The async/await and Task.Delay technique works great for running in other threads and being able to change the timing on the fly.

    Even in non-PCL projects I always tell people to abandon the System.Threading.Timer class. It's a mess.

  • CharwakaCharwaka INMember ✭✭✭✭✭

    Still If Any One Want to use System.Threading.Timer , Create

    ITimer timer = DependencyService.Get(); // In PCL Project

    public class SearchTimer : ITimer
    {
    //Create Time in Android Project
    }

Sign In or Register to comment.