Posso definire un lavoratore in background in un metodo?Background worker e garbage collection?
private void DownLoadFile(string fileLocation){
BackgroundWorker worker = new BackgroundWorker();
worker.DoWork += new DoWorkEventHandler((obj, args) => {
// Will be executed by back ground thread asynchronously.
args.Result = Download(fileLocation);
});
worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler((obj, args) => {
// will be executed in the main thread.
Result r = args.Result as Result;
ReportResult(r);
});
worker.RunWorkerAsync(fileLocation);
}
Domanda: Se Scarica function() richiede molto tempo per scaricare il file, può GC calci in e ritirare oggetto operaio prima della RunWorkerCompleted() viene eseguito?
Si consiglia di utilizzare un delegato (azione (di stringa) dovrebbe fare) e quindi chiamare BeginInvoke. Non vedo alcun bisogno di BackgroundWorker in questo codice. È ancora possibile allegare un evento per quando il metodo è fatto. – JDB
Un modo migliore per farlo sarebbe quello di aggiungerlo alla coda del pool di thread utilizzando 'QueueUserWorkItem': http://msdn.microsoft.com/en-us/library/system.threading.threadpool.queueuserworkitem.aspx –
@ J ... Il threadpool è bello, ma rende più difficile la gestione della richiamata * a destra SynchronizationContext *. La TPL lo gestisce bene, però. –