我是新來的C#編程,我有一個任務,使一個進程從單線程多線程。我正在使用C#3.5版本並在代碼中實現threadpool。我已經搜索了關於線程池並做了一些更改,但它不起作用。當我再次在互聯網上搜索時,我認爲我只寫了部分代碼,只排隊用戶工作項,我不知道如何執行這些線程。如何在C#中排隊用戶工作項之後執行線程池?
這裏顯示的是我寫的代碼,如果代碼錯誤請不要猶豫糾正我,我對C#編碼非常陌生。
ThreadPool.SetMaxThreads(6, 6);
try
{
// Assign the values to the report parameters
for (int i = 0; i < aq.Count; i++)
{
object j = aq[i];
ThreadPool.QueueUserWorkItem(new WaitCallback(process), j);
}
}
private void process(object i)
{
List<Report> aq = new List<Report>();
ReportEnv env = null;
ParameterValue[] paramval;
List<Report> list = new List<Report>();
Report al = null;
using (OleDbDataAdapter oleDA = new OleDbDataAdapter())
using (DataTable dt = new DataTable())
{
oleDA.Fill(dt, i);
foreach (DataRow _row in dt.Rows)
{
al = new Report();
al.EmailAttachmentMsg = _row["AttachmentMsg"].ToString();
al.reportName = _row["Repo"].ToString();
al.AccountNumber = _row["Number"].ToString();
al.AccountGroupCode = _row["GroupCode"].ToString();
al.EmailTo = _row["To"].ToString().Split(';');
al.ReportScheduleId = _row["ReportScheduleId"].ToString();
al.Frequency = _row["Frequency"].ToString();
al.ColcoContactTelephone = _row["ColcoContactTelephone"].ToString();
list.Add(al);
}
}
// aq = Populatereport(Dts.Variables["vnSource_SQL_Result"].Value);
env = PopulateEnvironment(Dts.Variables["vnEnvironment"].Value);
aq = list;
paramval = new ParameterValue[2];
paramval[0] = new ParameterValue();
paramval[0].Name = "PRM_CustomerDetails";
paramval[0].Value = aq[0].AccountNumber;
paramval[1] = new ParameterValue();
paramval[1].Name = "PRM_Startdate";
paramval[1].Value = aq[0].StartDate;
//Rendering the report begins
ReportExecutionService rs = new ReportExecutionService();
rs.Credentials = System.Net.CredentialCache.DefaultCredentials;
rs.Url = env.SSRSServerUrl.ToString();
//Load the report options
rs.LoadReport(aq[0].ReportPath, null);
rs.SetExecutionParameters(paramval, aq[0].CultureCode);
// Set the filename
String filename = aq[0]. Number + "_" + env.Code + "_" + "_" + aq[0].Name +
DateTime.UtcNow.ToString("_dd-MM-yyyy_hh-mm-ss.fff");
//Render the report and generate pdf
Byte[] results;
string encoding = String.Empty;
string mimeType = String.Empty;
string extension = String.Empty;
Warning[] warnings = null;
string[] streamIDs = null;
string deviceInfo = null;
results = rs.Render(aq[0].ReportFormat, deviceInfo, out extension, out encoding, out mimeType, out warnings, out streamIDs);
//Write the file into the directory
using (FileStream stream = File.OpenWrite(@env.wipPath + filename))
{
stream.Write(results, 0, results.Length);
}
if (SendEmail(env.From, aq[0].To, env.Subject, aq[0].Attachment, env.Server, false, filename, env.TimeOut) == true)
{
// Move report file from WIP to Processed
File.Move(@env.oldPath + filename, @env.newPath + filename);
}
}
這看起來並不像部分代碼給我。它應該工作。什麼表明它不起作用?你在process()上做了一個斷點嗎? – Tyress
你在等待主線程嗎?我假設如此。如果不是,排隊的線程可能永遠不會執行。 – Venki
請參閱此http://stackoverflow.com/questions/14515207/whats-the-proper-way-to-use-a-threadpool – Venki