我能做出像
这样的功能吗?public void myfunc()
{
//some processing
}
一个线程函数
Thread t = new Thread (new ThreadStart (myfunc));
然后一些
t.Start();
我可以将任何类型的参数传递给它吗?
答案 0 :(得分:7)
有一个重载接受一个对象状态 - 但是,IMO是将任意参数传递给一个threadstart(并在编译时验证签名)的最简单方法是使用匿名方法:
int a = ...
string b = ...
Thread t = new Thread (delegate() { SomeFunction(a,b);});
只是(这是重要) - *之后不要更改a
或b
,因为更改会反映到主题(作为比赛) ) - 即不要这样做:
int a = ...
string b = ...
Thread t = new Thread (delegate() { SomeFunction(a,b);});
a = 12; // this change will be visible to the anonymous method - be careful ;-p
在循环的情况下,重要的是(在处理异步和捕获的变量时)为此引入额外的变量;这些非常不同
int[] data = {1,2,3,4,5};
foreach(int i in data) {
ThreadPool.QueueUserWorkItem(delegate {
Console.WriteLine(i); });
}
Console.ReadLine();
(可能打印5,5,5,5,5)
int[] data = {1,2,3,4,5};
foreach (int i in data) {
int tmp = i;
ThreadPool.QueueUserWorkItem(delegate {
Console.WriteLine(tmp); });
}
Console.ReadLine();
(将以无特定顺序打印1-5)
更新以讨论Meeh的观点(评论);什么打印(99.999%的时间 - 有竞争条件)?
string s = "dreams";
ThreadPool.QueueUserWorkItem(delegate {
Console.WriteLine(s);
});
s = "reality";
Console.ReadLine();
答案 1 :(得分:6)
理论上,你可以让任何方法在一个单独的线程中执行,只要你遵循一些规则(例如同步,调用代理来更新ui等)。
从您的问题我了解到您对多线程编程没有太多经验,所以我建议您阅读很多关于线程的知识,并了解可能出现的危险和问题。您也可以使用承担部分职责的后台工作者类。
另外,是的,您可以将参数传递给线程方法:
private class ThreadParameters
{
....
}
...
public void ThreadFunc(object state)
{
ThreadParameters params = (ThreadParameters)state;
....
}
Thread t = new Thread(new ParameterizedThreadStart(ThreadFunc));
t.Start(new ThreadParameters() { ... });
答案 2 :(得分:1)
protected void Page_Load(object sender, EventArgs e)
{
if (Session["intCompany_Accounting_Year_ID"] == null || Session["vcrAdmin_Id"] == null)
{
Response.Redirect("User_Login.aspx");
}
if (!IsPostBack)
{
ViewState["Page_Index"] = Request.QueryString["Page_Index"];
ViewState["ID_Field"] = Request.QueryString["ID_Field"];
Initialize_Page();
Bind_Search_Grid();
}
}
protected void btnFind_Click(object sender, EventArgs e)
{
Bind_Search_Grid();
}
protected void grdSearch_Result_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Header)
{
Label lblHeader = (Label)e.Row.FindControl("lblHeader");
lblHeader.Text = ViewState["Header_Name"].ToString();
}
else if (e.Row.RowType == DataControlRowType.DataRow)
{
LinkButton lnk = (LinkButton)e.Row.FindControl("lnkDisplay_Text");
lnk.OnClientClick = "Close_Window('" + lnk.CommandArgument + "','" + ViewState["ID_Field"].ToString()
+ "')";
}
}
protected void grdSearch_Result_RowCreated(object sender, GridViewRowEventArgs e)
{
e.Row.Cells[1].Visible = false;
e.Row.Cells[2].Visible = false;
e.Row.Cells[3].Visible = false;
}
}