1:有人可以向我解释第一个功能的最后一行吗?
2:第二个功能不起作用。请告诉我原因.PHP脚本正在获取数据。
我编辑了代码以获取此功能,但应用程序现在崩溃了一个System nullreferenceexception。 请帮忙。
private void checkbutton_Click(object sender, RoutedEventArgs e)
{
statustext.Text = "Checking for new score";
var webclient = new WebClient();
webclient.OpenReadCompleted += new OpenReadCompletedEventHandler(getscores_OpenReadCompleted);
webclient.OpenReadAsync(new Uri("http://example.com/get.php?"+DateTime.Now));
}
void getscores_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
StreamReader s = null;
Stream reply=null;
try
{
reply = (Stream)e.Result;
s = new StreamReader(reply);
}
catch
{
statustext.Text = "ERROR IN FETCHING";
}
scorebox.Text = s.ReadToEnd();
statustext.Text = "DoNE";
}
答案 0 :(得分:6)
第一种方法的最后一行是将处理程序附加到事件。它说当OpenReadCompleted
事件触发时,也就是说当读取完成时,应该调用getscores_OpenReadCompleted
方法。
getscores_OpenReadCompleted
不起作用,因为它试图从非UI线程访问UI元素。
您还在启动异步操作后添加处理程序,因此虽然不太可能,但操作很可能很快完成非常并且在添加处理程序之前触发了事件。虽然这种情况非常异常,但只需在启动异步操作之前添加处理程序,就可以非常快速,轻松地修复它。
答案 1 :(得分:0)
这里有几个问题:
OpenReadAsync
private void checkbutton_Click(object sender, RoutedEventArgs e)
{
statustext.Text = "Checking for new score";
var webclient = new WebClient();
webclient.OpenReadCompleted += new OpenReadCompletedEventHandler(getscores_OpenReadCompleted);
webclient.OpenReadAsync(new Uri("http://example.com/get.php?"+DateTime.Now));
}
void getscores_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
Stream reply = null;
StreamReader s = null;
string outputText = string.Empty;
try
{
reply = (Stream)e.Result;
s = new StreamReader(reply);
outputText = s.ReadToEnd();
}
finally
{
if (s != null)
{
s.Close();
}
if (reply != null)
{
reply.Close();
}
}
statustext.Text = outputText;
}
请在此处查看OpenReadAsync
方法的用法: