简体   繁体   中英

ObjectDisposedException: Cannot access a disposed object. Object name: 'Dispatcher'

I'm getting an error:

ObjectDisposedException: Cannot access a disposed object. Object name: 'Dispatcher'.

My code in 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);
    }

I observed that it returns no error when I delete a line in webClient_DownloadStringCompleted. Any ideas or more code needed?

The scope of webclient is limited to the public CultureEventViewModel() instantiation (in other words it can be garbage collected as soon as the object is instantiated. Because there is an outstanding asynchronous task being performed (DownloadStringAsync) the garbage collector can not collect your webClient object.

Once the string has been downloaded the webClient is fair game and can be disposed of. To keep the web client you need to give it an existance outside the instantiation.

for example

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

...

but note that this will not dispose of the webclient instance untill the class instance is disposed of.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM