ObjectDisposedException:无法访问已处置的对象。对象名称:' Dispatcher'

时间:2014-07-18 13:03:07

标签: c# xaml windows-phone-8

我收到了一个错误:

ObjectDisposedException:无法访问已处置的对象。对象名称:'Dispatcher'。

我在模型视图中的代码:

public CultureEventViewModel()
{
    CultureEvents = new List<CultureEvent>();
    WebClient webClient = new WebClient();
    webClient.DownloadStringCompleted += new DownloadStringCompletedEventHandler(webClient_DownloadStringCompleted);
    webClient.DownloadStringAsync(new Uri("sampleuri"));
}

    public void webClient_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
    {  
        CultureEvents = JsonConvert.DeserializeObject<List<CultureEvent>>(e.Result);
    }

我发现在webClient_DownloadStringCompleted中删除一行时没有返回任何错误。是否需要任何想法或更多代码?

1 个答案:

答案 0 :(得分:0)

webclient的范围仅限于公共CultureEventViewModel()实例化(换句话说,一旦对象被实例化,它就可以被垃圾收集。因为执行了一个未完成的异步任务(DownloadStringAsync),垃圾收集器不能收集你的webClient对象。

一旦下载了字符串,webClient就是公平游戏,可以被处理掉。要保留Web客户端,您需要在实例化之外提供它。

例如

Class CultureEventViewModel
private WebClient webclient
public CultureEventViewModel()
{
    CultureEvents = new List<CultureEvent>();
    WebClient webClient = new WebClient();

...

但请注意,这不会处理webclient实例,直到处理类实例。