Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When using a delegate, is there a way to get hold of the object response?

As an example:

WebClient.DownloadStringAsync Method (Uri)

Normal code:

private void wcDownloadStringCompleted( 
    object sender, DownloadStringCompletedEventArgs e)
{ 
    // The result is in e.Result
    string fileContent = (string)e.Result;
}

public void GetFile(string fileUrl)
{
    using (WebClient wc = new WebClient())
    {
        wc.DownloadStringCompleted += 
             new DownloadStringCompletedEventHandler(wcDownloadStringCompleted);
        wc.DownloadStringAsync(new Uri(fileUrl));
    }
}

But if we use an anonymous delegate like:

public void GetFile(string fileUrl)
{
    using (WebClient wc = new WebClient())
    {
        wc.DownloadStringCompleted += 
            delegate {
                // How do I get the hold of e.Result here?
            };
        wc.DownloadStringAsync(new Uri(fileUrl));
    }
}

How do I get the hold of e.Result there?

like image 324
balexandre Avatar asked Dec 10 '22 05:12

balexandre


1 Answers

wc.DownloadStringCompleted += 
            (s, e) => {
                var result = e.Result;
            };

or if you like the delegate syntax

wc.DownloadStringCompleted += 
            delegate(object s, DownloadStringCompletedEventArgs e) {
                var result = e.Result;
            };
like image 89
PHeiberg Avatar answered May 16 '23 09:05

PHeiberg