![]() |
C# try catch Probleme
Ich stehe da grad etwas aufm Schlauch:
Code:
Um searcher.FindAll(); würde ich gernen nen try catch Block legen, weil da allerhand passieren kann. Ich kriege es aber irgendwie nicht hin, dass ich am Ende noch results.Dispose(); aufrufen kann.
[...]
SearchResultCollection results = searcher.FindAll(); //dostuff [...] results.Dispose(); Ist wahrscheinlich ne einfache Sache, aber ich kenne mich in C# noch praktisch gar nicht aus. Versucht habe ich folgendes:
Code:
Klappt nicht, weil results nur im try-Block selbst gültig ist.
try
{ SearchResultCollection results = searcher.FindAll(); //dostuff [...] } catch (Exception ex) // { return ex.Message; } finally { results.Dispose(); }
Code:
Da gibt's die Meldung "Verwendung der nicht zugewiesenen Variable 'results' "
SearchResultCollection results;
try { results = searcher.FindAll(); //dostuff [...] } catch (Exception ex) // { return ex.Message; } finally { results.Dispose(); } Aber wenn ich es noch anders anordne, wird results.Dispose(); bei nem Fehlerfall nicht aufgerufen. Was übersehe ich da? |
AW: C# try catch Probleme
Du vergisst den Garbage Collector glaub ich :)
![]() |
AW: C# try catch Probleme
Für die Arbeit mit disposable Objekten gibt es das using Pattern:
Code:
Mehr Infos gibt es hier:
using(SearchResultCollection results = searcher.FindAll())
{ DoStuff(results); } // <-- Implizieter Aufruf von results.Dispose sobald die Using-Sektion verlassen wird. Kein Try-Finally erforderlich ![]() |
AW: C# try catch Probleme
Zitat:
Sollte so klappen(alternativ zu using):
Code:
SearchResultCollection results = null;
try { results = searcher.FindAll(); //dostuff [...] return results.ToString() // o.ä. } catch (Exception ex) // { return ex.Message; } finally { if(results != null) results.Dispose(); } |
AW: C# try catch Probleme
Danke, das hat funktioniert! :thumb:
|
Alle Zeitangaben in WEZ +1. Es ist jetzt 21:55 Uhr. |
Powered by vBulletin® Copyright ©2000 - 2025, Jelsoft Enterprises Ltd.
LinkBacks Enabled by vBSEO © 2011, Crawlability, Inc.
Delphi-PRAXiS (c) 2002 - 2023 by Daniel R. Wolf, 2024 by Thomas Breitkreuz