ObjectDisposedException:不能访问被处置的对象.对象名称:'Dispatcher'

本文关键字:对象 Dispatcher 访问 不能 ObjectDisposedException | 更新日期: 2023-09-27 18:13:25

出现错误:

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

我在modelview中的代码:
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中删除一行时,它没有返回错误。有什么想法或需要更多的代码吗?

ObjectDisposedException:不能访问被处置的对象.对象名称:'Dispatcher'

webclient的作用域仅限于公共CultureEventViewModel()实例化(换句话说,它可以在对象实例化后立即被垃圾收集)。因为有一个未完成的异步任务正在执行(DownloadStringAsync),垃圾收集器不能收集你的webClient对象。

一旦字符串被下载,webClient是公平的游戏,可以处理。为了保持web客户端,你需要在实例化之外给它一个存在。

例如

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

但是注意,在类实例被处理掉之前,这不会处理webclient实例。