Witam
Znalazłem w sieci przykład pobierania asynchronicznego.
Chciałbym umieścić go w osobnej klasie, a nie dołączać do głównej klasy mojego programu.
Z mojej klasy wywołuję:
Net.ScanSites("http://www.jakas.strona");
Nie wiem jak powiadomić główną klasę o zdarzeniach tj. zakończenie downloadu czy przekazanie wyniku.
Próbowałem z delegatami, ale nie udało mi się nic sensownego zrobić. Oto kod:
public class Net
{
public static void ScanSites(string uriString)
{
WebRequest request = HttpWebRequest.Create(uriString);
request.Method = "GET";
object data = new object(); //container for our "Stuff"
// RequestState is a custom class to pass info to the callback
RequestState state = new RequestState(request, data, uriString);
IAsyncResult result = request.BeginGetResponse(new AsyncCallback(WwwSrc), state);
//Register the timeout callback
ThreadPool.RegisterWaitForSingleObject(
result.AsyncWaitHandle,
new WaitOrTimerCallback(ScanTimeoutCallback),
state,
(10 * 1000), // 10 second timeout
true
);
}
private static void WwwSrc(IAsyncResult result)
{
try
{
// grab the custom state object
RequestState state = (RequestState)result.AsyncState;
WebRequest request = (WebRequest)state.Request;
// get the Response
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(result);
//jesli bylo abort dalej nie idzie
Stream s = (Stream)response.GetResponseStream();
StreamReader readStream = new StreamReader(s);
// dataString will hold the entire contents of the requested page if we need it.
string dataString = readStream.ReadToEnd(); //<< tutaj zawartosc strony
response.Close();
s.Close();
readStream.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private static void ScanTimeoutCallback(object state, bool timedOut)
{
if (timedOut)
{
RequestState reqState = (RequestState)state;
if (reqState != null)
reqState.Request.Abort();
//Console.WriteLine("aborted- timeout");
}
}
}
public class RequestState
{
public WebRequest Request; // holds the request
public object Data; // store any data in this
public string SiteUrl; // holds the UrlString to match up results (Database lookup, etc).
public RequestState(WebRequest request, object data, string siteUrl)
{
this.Request = request;
this.Data = data;
this.SiteUrl = siteUrl;
}
}