将单线程c#代码转换为多线程代码
本文关键字:代码 多线程 转换 单线程 | 更新日期: 2023-09-27 18:06:57
我有下面的代码,我想转换为多线程使用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
}
}
谢谢
先拆分逻辑
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
更新UI
我发现最简单的方法是使用Parallel.ForEach
方法,而不是
foreach (DataRow dr in dsResult.Tables[0].Rows)
使用 Parellel.Foreach(dsResult.Tables[0].Rows, dr =>
{
//foreach body code goes here.
});
然而,如果你试图更新一个操纵UI以利用并发性的算法,你将会有一个糟糕的时间。Win表单应用程序(如果我没记错的话,Win 8/phone应用程序)不允许从主线程以外的任何线程操作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!";}
}