Простите слоупока, но как из другого потока обновить control на форме?
Пробовал сюда прикрутить delegate, но как-то безуспешно.
Передача должна происходить из функции SendStr.
using ...;
namespace Ping_test
{
public delegate void Del(string str);
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
Del Call = new Del(UpdateRes);
}
private void button1_Click(object sender, EventArgs e)
{
new PingExample().Start( "192.168.1.1",10);
}
}
public class PingExample
{
private int Count = 0;
private int Cycle = 0;
private string ip = string.Empty;
public PingExample()
{
TTimer = new System.Threading.Timer(new TimerCallback(OnTimer), TimerRun, System.Threading.Timeout.Infinite, 1000);
}
public void Start(string ip_str, int Raz)
{
Count = 1;
Cycle = Raz;
ip = ip_str;
TTimer.Change(0, 1000);
}
private void OnTimer(object state)
{
if (Count <= Cycle)
{
Go();
}
}
public void Go()
{
AutoResetEvent waiter = new AutoResetEvent(false);
Ping pingSender = new Ping();
pingSender.PingCompleted += new PingCompletedEventHandler(PingCompletedCallback);
string data = "ID:<" + String.Format(@"{0,5:d}", Count.ToString()) + ">**********************";
byte[] buffer = Encoding.ASCII.GetBytes(data);
int timeout = 1000;
PingOptions options = new PingOptions(64, true);
pingSender.SendAsync(ip, timeout, buffer, options, waiter);
}
private void PingCompletedCallback(object sender, PingCompletedEventArgs e)
{
// If the operation was canceled, display a message to the user.
if (e.Cancelled)
{
Console.WriteLine("Ping canceled.");
((AutoResetEvent)e.UserState).Set();
}
if (e.Error != null)
{
Console.WriteLine("#" + Count.ToString() + " " + ip + " Ping failed: ");
Console.WriteLine(e.Error.ToString());
((AutoResetEvent)e.UserState).Set();
}
PingReply reply = e.Reply;
DisplayReply(reply);
((AutoResetEvent)e.UserState).Set();
Count++;
}
public void DisplayReply(PingReply reply)
{
if (reply == null)
return;
string Num = "#" + String.Format(@"{0,5:d}", Count.ToString());
if (reply.Status == IPStatus.Success)
{
string res = Num + " " + reply.Address.ToString() + " RTT " + reply.RoundtripTime.ToString() + " TTL " + reply.Options.Ttl.ToString() + " BUFFER " + reply.Buffer.Length.ToString();
res += " \"" + System.Text.ASCIIEncoding.ASCII.GetString(reply.Buffer) + "\"";
SendStr(res);
}
else
{
string res = Num + " " + ip + " ERROR: " + reply.Status.ToString();
SendStr(res);
}
}
void SendStr(string str);
{
}
}