我有以下代码,我想使用c#4.0转换为多线程。有可能吗?非常感谢任何指导。
我有一个按钮开始启动过程,它调用以下函数
private void ProcessData()
{
//clear some ui text fields and disable start button and enable cancel button and set status to working
//open database connection
try
{
//populate ui multi line textbox saying that it is getting data from database
var dsResult = new DataSet();
//populate dataset
//populate ui multi line textbox saying that it finished getting data from database
//close connection
if (dsResult.Tables.Count == 1 && dsResult.Tables[0].Rows.Count > 0)
{
//populate another field saying how much records we got
int iCount = 1;
foreach (DataRow dr in dsResult.Tables[0].Rows)
{
if (_stop)
{
//set the status as forced stop
return;
}
//populate the currently processed record count using iCount
//populate ui multi line textbox indicating which item that it is starting to work using dr["Item"]
//call some external function to process some data, inside this function i have to update ui multi line textbox as well
var dataFile = SearchDataFile(dr["Item"].ToString());
if (dataFile == null)
{
//populate ui multi line textbox indicating that item was not found
iCount++;
continue;
}
//call another external function to process some data, inside this function i have to update ui multi line textbox as well
UpdateDataFile(dataFile, folderId, dr, dr["Item"].ToString());
iCount++;
}
}
else
{
//populate ui multi line textbox indicating no data found
}
//update status saying that it is complete
tsslblStatus.Text = "STATUS : COMPLETE";
}
catch (Exception ex)
{
//close connection
//populate ui multi line textbox indicating error occured
//update status to error
}
finally
{
//re adjust ui and enabling start and disable stop
//set _stop variable to false
}
}
由于
答案 0 :(得分:0)
首先拆分你的逻辑
SomeJobA();
SomeJobB();
SomeJobC();
...
然后做一些多线程
start SomeJobA() thread/task
start SomeJobB() thread/task
start SomeJobC() thread/task
...
to wait or not to wait for them to finish?
要使用其他帖子更新用户Invoke
/ BeginInvoke
。
答案 1 :(得分:0)
我发现最简单的方法是使用Parallel.ForEach
方法,而不是
foreach (DataRow dr in dsResult.Tables[0].Rows)
使用
Parellel.Foreach(dsResult.Tables[0].Rows, dr =>
{
//foreach body code goes here.
});
但是,如果您尝试更新操纵UI的算法以利用并发性,那么您将遇到不好的时间。 Win form应用程序(如果我没记错,Win 8 /手机应用程序)不允许您从主线程以外的任何线程操作UI(即写入文本框)。
为了正确并行化此算法,您需要分离出操作UI的所有代码。
您可以使用TaskFactory
整理您想要并行完成的工作:
public class MyState{
public string Example {get;set;}
}
private MyState _state;
private void MethodCalledFromUIThread()
{
//Update UI.
TextBox1.Text = string.Empty;
//Start parallel work in a new thread.
new TaskFactory().StartNew(() => ThreadedMethod())
//Wait for background threads to complete
.Wait();
//Update UI with result of processing.
TextBox1.Text = _state.Example;
}
private void ThreadedMethod()
{
//load dsResult
Parallel.ForEach(dsResult.Tables[0].Rows, dr =>
{
//process data in parallel.
}
//Update the State object so the UI thread can get access to the data
_state = new MyState{Example = "Data Updated!";}
}