这是我制作的代码,它通常有效,但有时会失败(4次中有1次或多或少):
...
List<string> _items = new List<string>();
...
using (SqlCeConnection con = new SqlCeConnection(Globals.conString))
{
string codbultocomp = null;
con.Open();
using (SqlCeCommand cmd = new SqlCeCommand("SELECT codbultocomp FROM envios WHERE codigodestino=@codigodestino AND estado=@pendiente", con))
{
cmd.Parameters.AddWithValue("@codigodestino", codigoDestino);
cmd.Parameters.AddWithValue("@pendiente", "pendiente");
SqlCeDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
codbultocomp = reader["codbultocomp"].ToString();
_items.Add(codbultocomp);
}
reader.Close();
}
listBox1.DataSource = _items;
}
当它失败时,应用程序会冻结,如果我暂停调试,它会在最后一个大括号中停止。我尝试使用try / catch块显示错误,但它没有显示任何内容并停在同一个地方。我还试图观察列表框数据源在“监视”列表中显示此错误:
Unable to evaluate expression because the code is optimized or a native frame is on top of the call stack.
知道我做错了什么?
答案 0 :(得分:1)
在using
之后调用它,所有IDisposable对象将在using
之后处理。
...
List<string> _items = new List<string>();
...
using (SqlCeConnection con = new SqlCeConnection(Globals.conString))
{
...
}
listBox1.DataSource = _items;
答案 1 :(得分:1)
你为什么不尝试这样的事情:
对于明确的代码,请创建一个方法:
public List<string> getItems(string codigodestino, string pendiente)
{
List<string> _items = new List<string>();
SqlCeConnection con = new SqlCeConnection(Globals.conString);
string Qyery = "SELECT codbultocomp FROM envios WHERE codigodestino='" + codigodestino + "' AND estado='" + pendiente +"'";
try
{
con.Open();
SqlCeCommand cmd = new SqlCeCommand(Qyery, con);
cmd.CommandType = CommandType.Text;
SqlCeDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
_items.Add((string)reader["codbultocomp"]);
}
con.Close();
return _items;
}
catch (Exception ex)
{
throw ex;
}
finally
{
con.Dispose();
con.Close();
}
}
然后只使用:
listBox1.DataSource = getItems(codigoDestino, "pendiente");
答案 2 :(得分:0)
您只需关闭con对象即可。无需关闭阅读器。使用con对象需要注意。不需要休息。