Having trouble setting up a timer.

Joined
Jul 14, 2016
Messages
6
Programming Experience
10+
C#:
[FONT=Menlo][COLOR=#009695]using[/COLOR] System;
[COLOR=#009695]using[/COLOR] System.Threading;
[COLOR=#009695]using[/COLOR] System.Threading.Tasks;
[COLOR=#009695]using[/COLOR] System.Timers;

[COLOR=#009695]using[/COLOR] System.Collections.Generic;

[COLOR=#009695][/COLOR][/FONT][FONT=Menlo][COLOR=#009695]class[/COLOR] [COLOR=#3364a4]MainClass[/COLOR]
{
   [COLOR=#009695]private[/COLOR] [COLOR=#009695]static[/COLOR] [COLOR=#3364a4]Task[/COLOR] HandleTimer()
   {
      C[COLOR=#3364a4]onsole[/COLOR].WriteLine([COLOR=#db7100]"[/COLOR][COLOR=#a53e00]Tick[/COLOR][COLOR=#db7100]"[/COLOR]);
   }
   [COLOR=#009695]public[/COLOR] [COLOR=#009695]static[/COLOR] [COLOR=#009695]void[/COLOR] Main ([COLOR=#009695]string[/COLOR][] args)
   {
      Timer timer = [COLOR=#009695]new[/COLOR] Timer([COLOR=#db7100]1000[/COLOR]);                               [/FONT][FONT=Menlo]
      timer.Elapsed += [COLOR=#009695]async[/COLOR] (sender, e) => [COLOR=#009695]await[/COLOR] HandleTimer();
      timer.Start();
   }
}
[/FONT]

What are these error messages? I'm simply trying to setup a timer.

Error CS0104: `Timer' is an ambiguous reference between `System.Threading.Timer' and `System.Timers.Timer'
Error CS1061: Type `System.Threading.Timer' does not contain a definition for `Elapsed' and no extension method `Elapsed' of type `System.Threading.Timer' could be found. Are you missing an assembly reference?
Error CS1061: Type `System.Threading.Timer' does not contain a definition for `Start' and no extension method `Start' of type `System.Threading.Timer' could be found. Are you missing an assembly reference?
 
You have imported both the System.Threading and System.Timers namespaces and both contain a member named Timer, so when you use Timer unqualified in code it doesn't know which one you mean. That's what the first error message means. From your code, it appears that you want to use the System.Timers.Timer class so the second and third errors will disappear once you sort out the first.

If you don't need to use any members of the System.Threading namespace then remove that import and everything will work as is. If you need to keep that import then you have two options:

1. Qualify the Timer class when you use it in code:
var timer = new System.Timers.Timer(1000);

2. Import an alias for the Timer name:
using Timer = System.Timers.Timer;
 

Latest posts

Back
Top Bottom