tags:

views:

38

answers:

3

This is probably a basic question ..

void method1() 
{ 
    String VIP = "test";
    WebClient proxy = new WebClient();
    proxy.OpenReadCompleted += new OpenReadCompletedEventHandler(proxy_OpenReadCompleted);
    String urlStr = "someurl/lookup?q=" + keyEntityName + "&fme=1&edo=1&edi=1";
}



void proxy_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{ 

}

I need to access VIP in the proxy_OpenReadCompleted method. Pl. help

+1  A: 

There are two approaches to this. First is to pass the string as the second parameter in the OpenReadAsync call, this parameter becomes the value of the UserState property of the event args.

void method1() 
{ 
    String VIP = "test";
    WebClient proxy = new WebClient();
    proxy.OpenReadCompleted += proxy_OpenReadCompleted;
    String urlStr = "someurl/lookup?q=" + keyEntityName + "&fme=1&edo=1&edi=1";
    proxy.OpenReadAsync(new Uri(urlStr, UriKind.Relative), VIP);
}    

void proxy_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{ 
   String VIP = (string)e.UserState;
   // Do stuff that uses VIP.
}

Another approach is to access the variable directly using a closure:-

void method1() 
{ 
    String VIP = "test";
    WebClient proxy = new WebClient();
    proxy.OpenReadCompleted += (s, args) =>
    {
         // Do stuff that uses VIP.
    }
    String urlStr = "someurl/lookup?q=" + keyEntityName + "&fme=1&edo=1&edi=1";
    proxy.OpenReadAsync(new Uri(urlStr, UriKind.Relative), VIP);
}    
AnthonyWJones
+1  A: 
void method1() 
{ 
    String VIP = "test";
    WebClient proxy = new WebClient();
    proxy.OpenReadCompleted += (s,e) => proxy_OpenReadCompleted(s,e,VIP);
    String urlStr = "someurl/lookup?q=" + keyEntityName + "&fme=1&edo=1&edi=1";
}
PL
A: 

Be aware that if the async callback method writes into a databound variable, you are likely to get a cross-thread exception. You will need to use BeginInvoke() to get back to the UI thread. Here's an example using WCF services, but the principle is the same.

public void examsCallback(IAsyncResult result)
{
    try
    {
        EntityList<ExamEntity> examList = ((IExamService) result.AsyncState).EndGetAllExams(result);
        Deployment.Current.Dispatcher.BeginInvoke(() =>
        {
            foreach (ExamEntity exam in examList)
            {
                Exams.Add(exam);
            }
            ItemCount = Exams.Count;
            TotalItemCount = Exams.ItemCount;
        });
    }
    catch (Exception ex)
    {
        ErrorHandler.Handle(ex);
    }
}
Cylon Cat