Jim*_*Jim 4 c# silverlight windows-phone-7
现在WebClient问题已修复,可以在后台线程上返回,我想以这种方式开始使用它.
经过多次搜索,我想出了这个看起来工作正常的代码,这就是它的全部内容吗?
BackgroundWorker bw = new BackgroundWorker();
bw.DoWork += (s,e) =>
{
WebClient wc = new WebClient();
wc.DownloadStringCompleted += DownloadStringCompleted;
wc.DownloadStringAsync(url);
};
bw.RunWorkerAsync();
Run Code Online (Sandbox Code Playgroud)
在DownloadStringCompleted中,我将结果发送回UI线程.
我错过了什么重要的事情还是真的这么简单?
我不明白你为什么要首先WebClient
在后台线程上运行,因为WebClient
它已经为下载部分创建了一个线程.
不同之处在于WebClient DownloadStringCompleted
在UI线程上运行它的事件.它仍然会在你的代码中做什么.
我建议你改用WebRequest
班级.使用WebRequest
简单的扩展方法可以大大简化类的使用,使其行为类似于WebClient.
public static class WebRequestEx
{
public static void DownloadStringAsync(this WebRequest request, Action<string> callback)
{
if (request == null)
throw new ArgumentNullException("request");
if (callback == null)
throw new ArgumentNullException("callback");
request.BeginGetResponse((IAsyncResult result) =>
{
try
{
var response = request.EndGetResponse(result);
using (var reader = new StreamReader(response.GetResponseStream()))
{
callback(reader.ReadToEnd());
}
}
catch (WebException e)
{
// Don't perform a callback, as this error is mostly due to
// there being no internet connection available.
System.Diagnostics.Debug.WriteLine(e.Message);
}
}, request);
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
1889 次 |
最近记录: |