我真的不喜欢创建委托给线程功能。如果我当前正在使用方法A来做工作,但后来意识到最好在线程中运行,现在我必须创建一个委托和另一个方法来实际运行该线程。所以现在我有方法A起始线程,然后通过委托方法B工作。
我的问题是: * 我可以在线程声明中包装功能吗? *
像
这样的东西System.Threading.Thread t = new System.Threading.Thread(new System.Threading.ThreadStart(
new delegate()
{
SqlConnection Connection = Helpers.ConnectionHelper.CreateConnection();
SqlCommand cmd = new SqlCommand("MarkNotificationRead", Connection);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("@id", SqlDbType.BigInt).Value = this.id;
Connection.Open();
try
{
cmd.ExecuteNonQuery();
}
catch
{
}
Connection.Close();
});
我已经在某个地方看到过这样的事情,但不能再找到这个例子了。
答案 0 :(得分:0)
你所拥有的是非常接近的,只是轻微的句法变化 - 摆脱new
和()
:
System.Threading.Thread t = new System.Threading.Thread(new System.Threading.ThreadStart(
delegate
{
SqlConnection Connection = Helpers.ConnectionHelper.CreateConnection();
SqlCommand cmd = new SqlCommand("MarkNotificationRead", Connection);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("@id", SqlDbType.BigInt).Value = this.id;
Connection.Open();
try
{
cmd.ExecuteNonQuery();
}
catch
{
}
Connection.Close();
}));
另一种方法是使用lambda语法,你可以在其中摆脱ThreadStart
调用:
System.Threading.Thread t = new System.Threading.Thread(
() =>
{
...
});