I am trying to asynchronously resolve an IP address to host name using C# and then add the result to a ListBox. The asynchronous operation works alright but i can not add the resolved name to a listbox because another thread owns it. How can i bypass this issue and add the resolved name to a listbox.
here is what i’ve done so far
public static ManualResetEvent GetHostEntryFinished = new ManualResetEvent(false);
private void AsyncDNSResolver(string IPString)
{
GetHostEntryFinished.Reset();
IPHostEntry host = new IPHostEntry();
host.AddressList = new IPAddress[] { IPAddress.Parse(IPString) };
Dns.BeginGetHostEntry(host.AddressList[0], new AsyncCallback(GetHostEntryCallback), host);
GetHostEntryFinished.WaitOne();
}
public static void GetHostEntryCallback(IAsyncResult ar)
{
IPHostEntry host = (IPHostEntry)ar.AsyncState;
while (!ar.IsCompleted) ;
host = Dns.EndGetHostEntry(ar);
lsvHosts.items.add(host.HostName);
GetHostEntryFinished.Set();
}
If you wanted to execute an expensive activity on a separate thread and continue working while waiting for the result you can use this code snippet.
If you are using a Windows Forms application then the easiest way would be to use a
BackgroundWorker, here is a code sample