I have encountered this .NET compile time error, as shown below:
'Timer' is an ambiguous reference between 'System.Windows.Forms.Timer' and 'System.Threading.Timer'
It occurred after I added this code block for a clock:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net.Sockets;
using System.Threading;
using System.Security.Cryptography;
namespace SocketClient
{
public partial class SocketClient : Form
{
System.Net.Sockets.TcpClient clientSocket = new System.Net.Sockets.TcpClient();
NetworkStream serverStream = default(NetworkStream);
string readData = null;
public SocketClient()
{
InitializeComponent();
Timer timer = new Timer();
timer.Tick += new EventHandler(TimerOnTick);
timer.Interval = 1000;
timer.Start();
}
private void TimerOnTick(object sender, EventArgs ea)
{
Invalidate();
}
protected override void OnPaint(PaintEventArgs pea)
{
StringFormat strfmt = new StringFormat();
strfmt.Alignment = StringAlignment.Far;
strfmt.LineAlignment = StringAlignment.Far;
pea.Graphics.DrawString(DateTime.Now.ToString("F"),
Font, new SolidBrush(ForeColor),
ClientRectangle, strfmt);
}
private void getMessage()
{
while (true)
{
serverStream = clientSocket.GetStream();
int buffSize = 0;
byte[] inStream = new byte[10025];
buffSize = clientSocket.ReceiveBufferSize;
serverStream.Read(inStream, 0, buffSize);
string returndata = System.Text.Encoding.ASCII.GetString(inStream);
readData = "" + returndata;
msg();
}
}
private void msg()
{
if (this.InvokeRequired)
this.Invoke(new MethodInvoker(msg));
else
textDisplay.Text = textDisplay.Text + Environment.NewLine + " >> " + readData;
}
private void buttonConnect_Click(object sender, EventArgs e)
{
// show the message if no input is enter.
if (string.IsNullOrEmpty(textName.Text) || string.IsNullOrEmpty(textPort.Text) || string.IsNullOrEmpty(textIP.Text))
{
MessageBox.Show("Please enter Name, IP Address & Port #");
}
else
{
//connect to the server if all 3 input is enter
readData = "Conected to NYP Server ...";
msg();
clientSocket.Connect(textIP.Text, Convert.ToInt32(textPort.Text));
serverStream = clientSocket.GetStream();
byte[] outStream = System.Text.Encoding.ASCII.GetBytes(textName.Text + "$");
serverStream.Write(outStream, 0, outStream.Length);
serverStream.Flush();
Thread ctThread = new Thread(getMessage);
ctThread.Start();
}
}
private void buttonSend_Click(object sender, EventArgs e)
{
// Show msg box if no server is connected
if (serverStream == null)
{
MessageBox.Show("Please connect to a server first!");
return;
}
// Send text
byte[] outStream = System.Text.Encoding.ASCII.GetBytes(textSend.Text + "$");
serverStream.Write(outStream, 0, outStream.Length);
serverStream.Flush();
// Clear text
textSend.Text = "";
}
private void textDisplay_TextChanged(object sender, EventArgs e)
{
textDisplay.SelectionStart = textDisplay.Text.Length;
textDisplay.ScrollToCaret();
textDisplay.Refresh();
}
private void textSend_TextChanged(object sender, EventArgs e)
{
buttonSend.Enabled = !string.IsNullOrEmpty(textSend.Text);
}
}
}
If I want to avoid this error, what are my options?
Здравствуйте. У меня проблемка. Есть такой код:
Код
using System; using System.IO; using System.Linq; using System.Collections.Generic; using System.Threading; namespace CSharp_Shell { public static class Program { public static void Main() { Timer timer = new Timer((t) => { Console.WriteLine("привет"); }); timer.Change(5000, 5000); Console.ReadKey(); } } }
и он работает, но мне нужно чтобы вместо console.writeline был msgbox. Я делаю вот так:
Код
using System; using System.IO; using System.Linq; using System.Collections.Generic; using System.Threading; using System.Windows.Forms; namespace CSharp_Shell { public static class Program { public static void Main() { Timer timer = new Timer((t) => { MessageBox.Show("привет","привет"); }); timer.Change(5000, 5000); Console.ReadKey(); } } }
Как вы заметили, я добавил using System.Windows.Forms;, потому что без него он не понимает что такое messagebox, но с ним есть ошибка
Неоднозначная ссылка «Timer» между «System.Threading.Timer» и «System.Windows.Forms.Timer» (CS0104).
Как исправить?
Я пытаюсь создать приложение формы Windows, и я хочу реализовать таймер.
public void timerStart()
{
DateTime now = DateTime.Now;
DateTime finish = base.taskEndDate;
finish = finish.AddHours(_appointmentTime.Hours); //_appointmentTime is a user defined value.
finish = finish.AddMinutes(_appointmentTime.Minutes);
finish = finish.AddMilliseconds(_appointmentTime.Milliseconds);
//Calculating the milliseconds left till task ends.
int daysLeft = finish.Day - now.Day;
int hoursLeft = finish.Hour - now.Hour;
int minsLeft = finish.Minute - now.Minute;
int secLeft = finish.Second - now.Second;
int milLeft = finish.Millisecond - now.Millisecond;
//Preparing to Start the timer.
TimeSpan end = new TimeSpan(daysLeft, hoursLeft, minsLeft, secLeft, minsLeft);
MessageBox.Show(end.ToString());
double x = end.TotalMilliseconds;
System.Timers.Timer _timer = new Timer(x);
}
Как я определил свой метод, но я получаю ошибку
'Timer' is an ambiguous reference between 'System.Windows.Forms.Timer' and 'System.Timers.Timer'
И я не уверен, как решить эту ошибку. Как только таймер закончится, я планирую сделать событие, которое предупредит пользователя. Я не хочу, чтобы таймер появился в форме.
2012-05-01 14:21
3
ответа
Решение
Вы, кажется, добавили оба using
Рекомендации (System.Windows.Forms
а также System.Timers
). Поэтому либо удалите один, либо полностью определите имя типа:
System.Timers.Timer _timer = new System.Timers.Timer(x);
user29407
01 май ’12 в 14:23
2012-05-01 14:23
2012-05-01 14:23
Вы можете устранить их неоднозначность, используя псевдоним типа, например так:
using System.Timers;
using Timer = System.Timers.Timer;
2012-05-01 14:26
Другие вопросы по тегам
c#
I am trying to make a timer that refreshes every 5 seconds. Here is my code:
using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Diagnostics;
using System.Timers;
namespace rpanel_server
{
public partial class MainForm : Form
{
public MainForm()
{
InitializeComponent();
Timer MyTimer = new Timer();
MyTimer.Interval = (4000);
MyTimer.Tick += new EventHandler(MyTimer_Tick);
MyTimer.Start();
}
private PerformanceCounter theMemCounter = new PerformanceCounter("Memory", "Available MBytes");
// Main stuff
public object getCPUCounter()
{
PerformanceCounter cpuCounter = new PerformanceCounter();
cpuCounter.CategoryName = "Processor";
cpuCounter.CounterName = "% Processor Time";
cpuCounter.InstanceName = "_Total";
// will always start at 0
dynamic firstValue = cpuCounter.NextValue();
System.Threading.Thread.Sleep(1000);
// now matches task manager reading
dynamic secondValue = cpuCounter.NextValue();
return secondValue;
}
void MainFormLoad(object sender, EventArgs e)
{
label8.Text = getCPUCounter() + "%";
label9.Text = theMemCounter.NextValue().ToString();
}
private void MyTimer_Tick(object sender, EventArgs e)
{
label8.Text = getCPUCounter() + "%";
label9.Text = theMemCounter.NextValue().ToString();
}
}
}
When I run that code, I get this:'Timer' is an ambiguous reference between 'System.Windows.Forms.Timer' and 'System.Timers.Timer' (CS0104)
No matter what timer I make, it will still throw that error. I don’t know what is wrong with this code.
Edited
by Djmann1013
Recommended Answers
The WinForms timer only runs in the UI thread. If you want to run in another thread, use another timer. I’d recommend
System.Timers.Timer
.
Jump to Post
In your first code remove
using System.Timers;
System.Timers contains a Timer to be used in a multithreaded environment. Just use the Forms Timer in your case. Hope it helps.
Jump to Post
All 7 Replies
deceptikon
1,790
Code Sniper
Team Colleague
Featured Poster
The .NET framework has three Timer
classes. One is in System.Windows.Forms
, one is in System.Timers
, and one is in System.Threading
. When you include more than one namespace with the same class name as a meber, the type must be fully qualified to resolve the ambiguity:
var MyTimer = new System.Timers.Timer();
Edited
by deceptikon
Now I get this:'System.Timers.Timer' does not contain a definition for 'Tick' and no extension method 'Tick' accepting a first argument of type 'System.Timers.Timer' could be found (are you missing a using directive or an assembly reference?) (CS1061)
deceptikon
1,790
Code Sniper
Team Colleague
Featured Poster
Apologies, I assumed you wanted the System.Timers
timer. But it looks like you’re trying to use the System.Windows.Forms
timer:
var MyTimer = new System.Windows.Forms.Timer();
This may be of use to you in chosing which to utilize.
Edited
by deceptikon
This seems to freeze the GUI, is there a way to use the timer without freezing the GUI?
deceptikon
1,790
Code Sniper
Team Colleague
Featured Poster
The WinForms timer only runs in the UI thread. If you want to run in another thread, use another timer. I’d recommend System.Timers.Timer
.
I used System.Timers.Timer in my code but nothing happens:
using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Diagnostics;
using System.Timers;
using System.Threading.Tasks;
namespace rpanel_server
{
public partial class MainForm : Form
{
public MainForm()
{
InitializeComponent();
}
private PerformanceCounter theMemCounter = new PerformanceCounter("Memory", "Available MBytes");
// Main stuff
public object getCPUCounter()
{
PerformanceCounter cpuCounter = new PerformanceCounter();
cpuCounter.CategoryName = "Processor";
cpuCounter.CounterName = "% Processor Time";
cpuCounter.InstanceName = "_Total";
// will always start at 0
dynamic firstValue = cpuCounter.NextValue();
System.Threading.Thread.Sleep(1000);
// now matches task manager reading
dynamic secondValue = cpuCounter.NextValue();
return secondValue;
}
void MainFormLoad(object sender, EventArgs e)
{
label8.Text = getCPUCounter() + "%";
label9.Text = theMemCounter.NextValue().ToString();
// Timer
System.Timers.Timer timer = new System.Timers.Timer(2000);
// Hook up the Elapsed event for the timer.
timer.Elapsed += new ElapsedEventHandler(MyTimer_Tick);
timer.Enabled = true;
timer.Start();
}
private void MyTimer_Tick(object source, ElapsedEventArgs e)
{
label8.Text = getCPUCounter() + "%";
label9.Text = theMemCounter.NextValue().ToString();
}
}
}
No errors or warnings are in the console.
ddanbe
2,724
Professional Procrastinator
Featured Poster
In your first code remove using System.Timers;
System.Timers contains a Timer to be used in a multithreaded environment. Just use the Forms Timer in your case. Hope it helps.
Reply to this topic
Be a part of the DaniWeb community
We’re a friendly, industry-focused community of developers, IT pros, digital marketers,
and technology enthusiasts meeting, networking, learning, and sharing knowledge.
See more:
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.IO.Ports; using System.Timers; namespace serialcomm { public partial class Form1 : Form { SerialPort ComPort = new SerialPort(); private Queue<byte> recievedData = new Queue<byte>(); public Form1() { InitializeComponent(); } private void ports_Click(object sender, EventArgs e) { string[] ArrayComPortsNames = null; int index = -1; string ComPortName = null; ArrayComPortsNames = SerialPort.GetPortNames(); do { index += 1; comboBox1.Items.Add(ArrayComPortsNames[index]); } while (!((ArrayComPortsNames[index] == ComPortName) || (index == ArrayComPortsNames.GetUpperBound(0)))); Array.Sort(ArrayComPortsNames); if (index == ArrayComPortsNames.GetUpperBound(0)) { ComPortName = ArrayComPortsNames[0]; } comboBox1.Text = ArrayComPortsNames[0]; cboBaudRate.Items.Add(300); cboBaudRate.Items.Add(600); cboBaudRate.Items.Add(1200); cboBaudRate.Items.Add(2400); cboBaudRate.Items.Add(9600); cboBaudRate.Items.Add(14400); cboBaudRate.Items.Add(19200); cboBaudRate.Items.Add(38400); cboBaudRate.Items.Add(57600); cboBaudRate.Items.Add(115200); cboBaudRate.Items.ToString(); cboBaudRate.Text = cboBaudRate.Items[0].ToString(); cboHandShaking.Items.Add("None"); cboHandShaking.Items.Add("XOnXOff"); cboHandShaking.Items.Add("RequestToSend"); cboHandShaking.Items.Add("RequestToSendXOnXOff"); cboHandShaking.Items.ToString(); cboHandShaking.Text=cboHandShaking.Items[0].ToString(); cboDataBits.Items.Add("7"); cboDataBits.Items.Add("8"); cboDataBits.Items.ToString(); cboDataBits.Text = cboDataBits.Items[0].ToString(); cboStopBits.Items.Add("One"); cboStopBits.Items.Add("OnePointFive"); cboStopBits.Items.Add("Two"); cboStopBits.Text = cboStopBits.Items[0].ToString(); cboParity.Items.Add("None"); cboParity.Items.Add("Even"); cboParity.Items.Add("Mark"); cboParity.Items.Add("Odd"); cboParity.Items.Add("Space"); cboParity.Text = cboParity.Items[0].ToString(); } private void button1_Click(object sender, EventArgs e) { if (button1.Text == "Closed") { button1.Text = "Open"; ComPort.PortName = Convert.ToString(comboBox1.Text); ComPort.BaudRate = Convert.ToInt32(cboBaudRate.Text); ComPort.DataBits = Convert.ToInt32(cboDataBits.Text); ComPort.StopBits = (StopBits)Enum.Parse(typeof(StopBits), cboStopBits.Text); ComPort.Handshake = (Handshake)Enum.Parse(typeof(Handshake), cboHandShaking.Text); ComPort.Parity = (Parity)Enum.Parse(typeof(Parity), cboParity.Text); ComPort.Open(); button1.BackColor = Color.Green; } else if (button1.Text == "Open") { button1.Text= "Closed"; ComPort.Close(); button1.BackColor = Color.Red; } } private void textBox1_TextChanged(object sender, EventArgs e) { } public class CommTimer { public Timer tmrComm = new Timer(); public bool timedout = false; public CommTimer() { timedout = false; tmrComm.AutoReset = false; tmrComm.Enabled = false; tmrComm.Interval = 1000; tmrComm.Elapsed += new ElapsedEventHandler(OnTimedCommEvent); } public void OnTimedCommEvent(object source, ElapsedEventArgs e) { timedout = true; tmrComm.Stop(); } public void Start(double timeoutperiod) { tmrComm.Interval = timeoutperiod; tmrComm.Stop(); timedout = false; tmrComm.Start(); } } private void button2_Click(object sender, EventArgs e) { string str = textBox1.Text; byte[] raw = new byte[textBox1.TextLength/2]; for (int i = 0; i < raw.Length; i++) { raw[i] = Convert.ToByte(str.Substring(i * 2, 2), 16); } ComPort.Write(raw,0,raw.Length); ComPort.DataReceived += new SerialDataReceivedEventHandler(sp_DataReceived); } private void sp_DataReceived(object sender, SerialDataReceivedEventArgs e) { int dataLength = ComPort.BytesToRead; byte[] data = new byte[dataLength]; int nbrDataRead = ComPort.Read(data, 0, data.Length); if (nbrDataRead == 0) return; CommTimer tmrComm = new CommTimer(); tmrComm.Start(4000); while ((ComPort.BytesToRead == 0) && (tmrComm.timedout == false)) { Application.DoEvents(); } if (data.Length > 0) { byte value = (byte)data.GetValue(0); textBox2.Text = Convert.ToString(value); } tmrComm.tmrComm.Dispose(); ComPort.DiscardInBuffer(); ComPort.DiscardOutBuffer(); ComPort.Close(); } private void textBox2_TextChanged(object sender, EventArgs e) { } private void Form1_Load(object sender, EventArgs e) { } } }
Updated 28-Oct-14 21:16pm
It’s pretty simple: you have using
statements which reference both namespaces:
using System.Windows.Forms; ... using System.Timers;
So when you type the name of a class (in this case Timer
) the compiler can’t be certain which Timer you mean: System.Windows.Forms.Timer[^] or System.Timers.Timer[^]
So you have to either remove the unnecessary using
statement; or fully qualify the namespace of the class you wanted:
public System.Windows.Forms.Timer tmrComm = new System.Windows.Forms.Timer();
Or
public System.Timers.Timer tmrComm = new System.Timers.Timer();
There is a name clash in you application, due to using
directives.
To fix it you may fully qualify the timer you intend to use, e.g.:
public System.Timers.Timer tmrComm = new System.Timers.Timer();
Of course you can write out the full namespace path:
System.Windows.Forms.Timer MyTimer = new System.Windows.Forms.Timer();
Another way is to create your own meaningful name for which Timer class you want to use by creating a .NET alias:
using SysTimerTimer = System.Timers.Timer; using WinFormTimer = System.Windows.Forms.Timer; using DiagnosticsStopwatchTimer = System.Diagnostics.Stopwatch; WinFormTimer MyTimer = new WinFormTimer();
Most applications that use a Timer in .NET can benefit from using the Stopwatch class in System.Diagnostics (.NET 2.0 and later): [^].
This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)