teixeira
Regular
Hi All,
I wanna make a class to check when my printer is connected or disconnected from the network.
This is for prevent user to send a job without the printer beeing online, and with this i wanna show some alarms.
This is using a normal socket connection, and i'm pinging the printer when i start the program and when i'm ready to send a job to it.
I use the ping class and after the event has been 'PingCompleted' raisen, i wanna make some actions, until here all well, but as the ping request is sent
assincronously i having some problems, because i wanna wait for ping status before i go ahead, see my code:
TIA
Tiago Teixeira
I wanna make a class to check when my printer is connected or disconnected from the network.
This is for prevent user to send a job without the printer beeing online, and with this i wanna show some alarms.
This is using a normal socket connection, and i'm pinging the printer when i start the program and when i'm ready to send a job to it.
I use the ping class and after the event has been 'PingCompleted' raisen, i wanna make some actions, until here all well, but as the ping request is sent
assincronously i having some problems, because i wanna wait for ping status before i go ahead, see my code:
Code:
/// <summary>
/// Pinga a Impressora com 32Bytes de lixo e espera o echo da mensagem para verificar se está ou n ligada
/// </summary>
/// <param name="ip">Ip da Impressora</param>
public static void CheckIfPrinterAlive(string ip)
{
//Notifica a thread que um determinado evento ocorreu
AutoResetEvent waiter = new AutoResetEvent(false);
//Cria uma instancia de ping
Ping pingSender = new Ping();
// When the PingCompleted event is raised,
// the PingCompletedCallback method is called.
pingSender.PingCompleted += new PingCompletedEventHandler(PingCompletedCallback);
// Create a buffer of 32 bytes of data to be transmitted.
string data = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
byte[] buffer = Encoding.ASCII.GetBytes(data);
// Wait 12 seconds for a reply.
int timeout = 12000;
// Set options for transmission:
// The data can go through 64 gateways or routers
// before it is destroyed, and the data packet
// cannot be fragmented.
PingOptions options = new PingOptions(64, true);
// Send the ping asynchronously.
// Use the waiter as the user token.
// When the callback completes, it can wake up this thread.
pingSender.SendAsync(ip, timeout, buffer, options, waiter);
//Here the code should stop until i get the ping reply
//How can i wait here until the assinchronous ping request has completed?
}
private static void PingCompletedCallback(object sender, PingCompletedEventArgs e)
{
PingReply reply = e.Reply;
if (reply.Status == IPStatus.Success)
{
printerAlive = true;
}
else
{
printerAlive = false;
}
// Let the main thread resume.
((AutoResetEvent)e.UserState).Set();
}
TIA
Tiago Teixeira