Delphi-PRAXiS

Delphi-PRAXiS (https://www.delphipraxis.net/forum.php)
-   Programmieren allgemein (https://www.delphipraxis.net/40-programmieren-allgemein/)
-   -   C# try catch Probleme (https://www.delphipraxis.net/193182-c-try-catch-probleme.html)

Rabenrecht 30. Jun 2017 14:15

C# try catch Probleme
 
Ich stehe da grad etwas aufm Schlauch:

Code:
[...]
SearchResultCollection results = searcher.FindAll();

//dostuff
[...]

results.Dispose();
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.
Ist wahrscheinlich ne einfache Sache, aber ich kenne mich in C# noch praktisch gar nicht aus.

Versucht habe ich folgendes:

Code:
try
{
   SearchResultCollection results = searcher.FindAll();

   //dostuff
   [...]
}
catch (Exception ex) //
{
   return ex.Message;
}
finally
{
   results.Dispose();
}
Klappt nicht, weil results nur im try-Block selbst gültig ist.

Code:
SearchResultCollection results;
try
{
   results = searcher.FindAll();

   //dostuff
   [...]
}
catch (Exception ex) //
{
   return ex.Message;
}
finally
{
   results.Dispose();
}
Da gibt's die Meldung "Verwendung der nicht zugewiesenen Variable 'results' "

Aber wenn ich es noch anders anordne, wird results.Dispose(); bei nem Fehlerfall nicht aufgerufen.

Was übersehe ich da?

Towmuz 30. Jun 2017 14:33

AW: C# try catch Probleme
 
Du vergisst den Garbage Collector glaub ich :)

https://msdn.microsoft.com/de-de/library/ms973837.aspx

Wosi 30. Jun 2017 15:17

AW: C# try catch Probleme
 
Für die Arbeit mit disposable Objekten gibt es das using Pattern:

Code:
using(SearchResultCollection results = searcher.FindAll())
{
  DoStuff(results);
} // <-- Implizieter Aufruf von results.Dispose sobald die Using-Sektion verlassen wird. Kein Try-Finally erforderlich
Mehr Infos gibt es hier: https://docs.microsoft.com/de-de/dot...sing-statement

wurzelzwerg 30. Jun 2017 18:58

AW: C# try catch Probleme
 
Zitat:

Zitat:

Da gibt's die Meldung "Verwendung der nicht zugewiesenen Variable 'results' "

Du musst null zuweisen.
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();
}

Rabenrecht 3. Jul 2017 08:12

AW: C# try catch Probleme
 
Danke, das hat funktioniert! :thumb:


Alle Zeitangaben in WEZ +1. Es ist jetzt 04:15 Uhr.

Powered by vBulletin® Copyright ©2000 - 2024, Jelsoft Enterprises Ltd.
LinkBacks Enabled by vBSEO © 2011, Crawlability, Inc.
Delphi-PRAXiS (c) 2002 - 2023 by Daniel R. Wolf, 2024 by Thomas Breitkreuz