I’ve got 2 webclient methods executing one after another.
Problem is, the first one that executes only finishes executing after the second one.
My main issue is that, in order for the second method to excecute, the first method first needs to complete because the second method requires data from the first method to execute successfully.
{
string name;
string surname;
string url1 =" //sample/1";
string url2 ="//sample/2";
//execution point!
public void ListBox_SelectionChagned(Object sender, SelectionChangedEventArgs e)
{
var sel = ((ListBox)ContextMenuPopup.Child).SelectedItem;
SubName = Convert.ToString(sel);
try
{
WebClient webClient = new WebClient();
Uri uri = new Uri(url1);
webClient.OpenReadCompleted += new OpenReadCompletedEventHandler(webClient_OpenReadCompleted1);
webClient.OpenReadAsync(uri);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
try
{
WebClient webClient = new WebClient();
Uri uri = new Uri(url2 + name);
webClient.OpenReadCompleted += new OpenReadCompletedEventHandler(webClient_OpenReadCompleted2);
webClient.OpenReadAsync(uri);
System.Diagnostics.Debug.WriteLine(url2 + name);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
//Method1
void webClient_OpenReadCompleted1(object sender, OpenReadCompletedEventArgs e)
{
DataContractJsonSerializer ser = null;
try
{
ser = new DataContractJsonSerializer(typeof(ObservableCollection<Subscriptions>));
ObservableCollection<Subscriptions> alldata = ser.ReadObject(e.Result) as ObservableCollection<Subscriptions>;
foreach (data _dt in alldata)
{
name = First_Name;
surname = Surname;
System.Diagnostics.Debug.WriteLine("My first name " + name);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
//Method2
void webClient_OpenReadCompleted2(object sender, OpenReadCompletedEventArgs e)
{
DataContractJsonSerializer ser = null;
try
{
ser = new DataContractJsonSerializer(typeof(ObservableCollection<Subscriptions>));
ObservableCollection<Subscriptions> alldata = ser.ReadObject(e.Result) as ObservableCollection<Subscriptions>;
foreach (data _dt in alldata)
{
name = First_Name;
surname = Surname;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
public class data
{
public string First_Name { get; set; }
public string Surname { get; set; }
}
}
Summary: I need to get the value”name” in the first method and use it to append my url2 in the second method?
but my second method completes before my first method?
Then Move the following code from selectionchanged event handler to the webClient_OpenReadCompleted1 event handler
that means, you have to make the second request after the successful completion of the first request.