How to access VIP in the proxy_OpenReadCompleted method?
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, OpenReadComplete开发者_StackOverflow中文版dEventArgs e)
{
}
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);
}
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";
}
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);
}
}
精彩评论