简体   繁体   English

我需要添加什么才能使用“ using System.Timers;”?

[英]What do I need to add to use “using System.Timers;”?

I work in xamarin forms and I need to use this assembly (using System.Timers;) but when I write it now it does not find Timers. 我以xamarin形式工作,我需要使用此程序集(使用System.Timers;),但是当我现在编写它时,它找不到Timers。 Do I need to add a package? 我需要添加包裹吗?

I want to use it like this: 我想这样使用它:

       var timer = new Timer (1000);
        timer.Elapsed += OnTimerElapsed;
        timer.Start ();

public static void OnTimerElapsed(object o, ElapsedEventArgs e)
{
 //code
 }

Do you want to use the Timer class in the PCL project? 是否要在PCL项目中使用Timer类? If so you will have to use Device.StartTimer 如果是这样,您将必须使用Device.StartTimer

Device.StartTimer (new TimeSpan (0, 0, 60), () => {
    // do something every 60 seconds
    return true; // runs again, or false to stop
});

System.Timers is coming from the System.dll assembly. System.Timers来自System.dll程序集。 Here is the inforamation from msdn 这是来自msdn的信息

Depending on the PCL profile, the Timer class won't be available. 根据PCL配置文件,Timer类将不可用。 I use this snippet of code instead: 我改用以下代码片段:

    delegate void TimerCallback(object state);

    sealed class Timer : CancellationTokenSource, IDisposable
    {
        internal Timer(TimerCallback callback, object state, int dueTime, int period)
        {
            if (dueTime <= 0)
                throw new ArgumentOutOfRangeException("dueTime", "Must be positive integer");

            if (period <= 0)
                throw new ArgumentOutOfRangeException("period", "Must be positive integer");

            Task.Delay(dueTime, Token).ContinueWith(async (t, s) =>
                {
                    var tuple = (Tuple<TimerCallback, object>)s;

                    while (true)
                    {
                        if (IsCancellationRequested)
                            break;
                        Task.Run(() => tuple.Item1(tuple.Item2));
                        await Task.Delay(period);
                    }

                }, Tuple.Create(callback, state), CancellationToken.None,
                TaskContinuationOptions.OnlyOnRanToCompletion,
                TaskScheduler.Default);
        }

        public new void Dispose()
        {
            Cancel();
        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM