我正在研究 Microsoft 企业库(数据应用程序 block )——样本 sln。
他们有一个异步读取数据的示例(IAsync
,虽然新版本(6)也支持async
)。
但 Resharper(或 visual studio- nevermind)向我显示:“访问已处置的闭包”:(首先我将显示图像,这样它会更清晰,然后我将粘贴代码)
代码:
/*1*/ [Description("Execute a command that retrieves data asynchronously")]
/*2*/ static void ReadDataAsynchronously()
/*3*/ {
/*4*/ if (!SupportsAsync(asyncDB)) return;
/*5*/
/*6*/ using(var doneWaitingEvent = new ManualResetEvent(false))
/*7*/ using(var readCompleteEvent = new ManualResetEvent(false))
/*8*/ {
/*9*/ try
/*10*/ {
/*11*/ // Create command to execute stored procedure and add parameters
/*12*/ DbCommand cmd = asyncDB.GetStoredProcCommand("ListOrdersSlowly");
/*13*/ asyncDB.AddInParameter(cmd, "state", DbType.String, "Colorado");
/*14*/ asyncDB.AddInParameter(cmd, "status", DbType.String, "DRAFT");
/*15*/ // Execute the query asynchronously specifying the command and the
/*16*/ // expression to execute when the data access process completes.
/*17*/ asyncDB.BeginExecuteReader(cmd,
/*18*/ asyncResult = >
/*19*/ {
/*20*/ // Lambda expression executed when the data access completes.
/*21*/ doneWaitingEvent.Set();
/*22*/ try
/*23*/ {
/*24*/ using(IDataReader reader = asyncDB.EndExecuteReader(asyncResult))
/*25*/ {
/*26*/ Console.WriteLine();
/*27*/ Console.WriteLine();
/*28*/ DisplayRowValues(reader);
/*29*/ }
/*30*/ }
/*31*/ catch (Exception ex)
/*32*/ {
/*33*/ Console.WriteLine("Error after data access completed: {0}", ex.Message);
/*34*/ }
/*35*/ finally
/*36*/ {
/*37*/ readCompleteEvent.Set();
/*38*/ }
/*39*/ }, null);
/*40*/
/*41*/ // Display waiting messages to indicate executing asynchronouly
/*42*/ while (!doneWaitingEvent.WaitOne(1000))
/*43*/ {
/*44*/ Console.Write("Waiting... ");
/*45*/ }
/*46*/
/*47*/ // Allow async thread to write results before displaying "continue" prompt
/*48*/ readCompleteEvent.WaitOne();
/*49*/ }
/*50*/ catch (Exception ex)
/*51*/ {
/*52*/ Console.WriteLine("Error while starting data access: {0}", ex.Message);
/*53*/ }
/*54*/ }
/*55*/ }
问题:
为什么会发出这个警告?有一个 manualreset-checked-signal
(在循环中运行)防止到达 using
子句 - 这意味着 - 没有 dispose
将调用 .
那么为什么它会大喊(警告)?
最佳答案
您将 doneWaitingEvent
传递给可能超出 using block 范围的 lambda。 IE。执行 lambda 时存在调用 Dispose
的风险。
关于c# - 访问 C# 中的处置闭包?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17620430/