I want the below process run continuously.But confused to use Thread or Task. I am also new in implementing Thread or Task.Is the process is right I am implementing? Between Thread and Task which is better for getting fast performance for long running process?
private void BtnStart_Click(object sender, EventArgs e)
{
IClockThread();
}
This method is creating thread for every machine.
public void IClockThread()
{
txtStatus.BeginInvoke((Action)(() => txtStatus.Text = "Thread for IClock Starts......" + Environment.NewLine));
Thread[] ts = new Thread[IclockDetails.Count];
for (int i = 0; i < 5; i++)
{
string IP = IclockDetails[i].IpAddress;
ts[i] = new Thread(() =>
{
ConnectMachineIClock(IP);
});
ts[i].Start();
}
txtStatus.BeginInvoke((Action)(() => txtStatus.Text += "Thread for IClock Ends............" + Environment.NewLine));
}
This is another method which is called by every thread.
public void ConnectMachineIClock(string IP)
{
int idwErrorCode = 0;
var Iclock = IclockDetails.Where(a => a.IpAddress == IP).FirstOrDefault();
if (AttnMachineRepository.IsMachineOnline(IP) == true)
{
Stopwatch sw = Stopwatch.StartNew();
blnCon = CZKEM1.Connect_Net(IP.Trim(), 4370);
sw.Stop();
if (blnCon == true)
{
UpdateText(1, txtStatus, Iclock.IpAddress);
iMachineNumber = Iclock.Id;
LocId = Iclock.LocationId;
MType = Iclock.MachineTypeId;
LocName = AttnMachineRepository.GetPunchLocation(LocId);
CZKEM1.RegEvent(iMachineNumber, 65535);
UpdateText(2, txtStatus, Iclock.IpAddress);
//txtStatus.BeginInvoke((Action)(() => txtStatus.Text += ("Connected with " + Iclock.IpAddress + " " + sw.Elapsed.TotalSeconds + " Seconds taken to connect") + Environment.NewLine));
MachineIP = Iclock.IpAddress;
Get_IClock_LogData(iMachineNumber);
}
else
{
CZKEM1.GetLastError(ref idwErrorCode);
UpdateText(-1, txtErrorLog, Iclock.IpAddress);
//txtErrorLog.BeginInvoke((Action)(() => txtErrorLog.Text += "Unable to connect the device with IP: " + MachineIP + ", ErrorCode = " + idwErrorCode.ToString() + "" + Environment.NewLine));
//Application.DoEvents();
}
}
else
{
UpdateText(-2, txtErrorLog, Iclock.IpAddress);
//txtErrorLog.BeginInvoke((Action)(() => txtErrorLog.Text += "IP " + MachineIP + " not found" + Environment.NewLine));
//Application.DoEvents();
}
}
public void UpdateText(int status, TextBox text, string IP)
{
switch (status)
{
case 1:
text.BeginInvoke((Action)(() => text.Text += ("Data Processing for" + IP + " starts") + Environment.NewLine));
Application.DoEvents();
break;
case 2:
text.BeginInvoke((Action)(() => text.Text += ("Connected with " + IP) + Environment.NewLine));
Application.DoEvents();
break;
case -1:
text.BeginInvoke((Action)(() => text.Text += "Unable to connect the device with IP: " + IP + ", ErrorCode = " + -1 + "" + Environment.NewLine));
Application.DoEvents();
break;
case -2:
text.BeginInvoke((Action)(() => text.Text += "IP " + IP + " not found" + Environment.NewLine));
Application.DoEvents();
break;
}
}