我有两个webclient方法一个接一个地执行。
问题是,第一个执行的只在第二个之后完成执行。
我的主要问题是,为了使第二种方法成功,第一种方法首先需要完成,因为第二种方法需要第一种方法的数据才能成功执行。
{
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; }
}
}
总结:我需要在第一个方法中获取值“name”并使用它在第二个方法中附加我的url2?
但我的第二种方法在我的第一种方法之前完成了吗?
答案 0 :(得分:0)
然后将以下代码从selectionchanged事件处理程序移动到webClient_OpenReadCompleted1事件处理程序
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);
这意味着,您必须在成功完成第一个请求后发出第二个请求。