如果我有一個返回一個字符串如下的方法:運行方法的線程,因爲它實在是太慢了
public string ExecuteCommandSync(object command)
{
string result = "";
try
{
System.Diagnostics.ProcessStartInfo procStartInfo =
new System.Diagnostics.ProcessStartInfo("cmd", "/c " + command);
procStartInfo.RedirectStandardOutput = true;
procStartInfo.UseShellExecute = false;
procStartInfo.CreateNoWindow = true;
System.Diagnostics.Process proc = new System.Diagnostics.Process();
proc.StartInfo = procStartInfo;
proc.Start();
result = proc.StandardOutput.ReadToEnd();
Console.WriteLine(result);
}
catch (Exception objException)
{
MessageBox.Show("error : " + objException.Message);
}
return result;
}
現在這工作正常爲小數據,但如果我有大量的數據搞得暈頭轉向..
如果我把這個線程將是更快速地爲大數據或至少改善,作爲即時通訊完全新的線程,我不知道如何與線程再次返回結果爲字符串...
能請有人幫忙。
感謝
編輯:
它是運行在Windows 7 基本思路是調用cmd命令和運行命令C#WinForm應用程序... 這是錯誤我從視覺工作室運行時:
The CLR has been unable to transition from COM context 0x8d85c0 to COM context 0x8d8730 for 60 seconds. The thread that owns the destination context/apartment is most likely either doing a non pumping wait or processing a very long running operation without pumping Windows messages. This situation generally has a negative performance impact and may even lead to the application becoming non responsive or memory usage accumulating continually over time. To avoid this problem, all single threaded apartment (STA) threads should use pumping wait primitives (such as CoWaitForMultipleHandles) and routinely pump messages during long running operations.
編輯2 :: 好了她e是我迄今所做
public string ExecuteCommandSync(object command)
{
string result = "";
try
{
backgroundWorker1.RunWorkerAsync(command);
}
catch (Exception objException)
{
MessageBox.Show("error : " + objException.Message);
}
return result;
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
string result;
Thread.Sleep(300);
object command = (object)e.Argument;
System.Diagnostics.ProcessStartInfo procStartInfo =
new System.Diagnostics.ProcessStartInfo("cmd", "/c " + command);
procStartInfo.RedirectStandardOutput = true;
procStartInfo.UseShellExecute = false;
procStartInfo.CreateNoWindow = true;
System.Diagnostics.Process proc = new System.Diagnostics.Process();
proc.StartInfo = procStartInfo;
proc.Start();
result = proc.StandardOutput.ReadToEnd();
}
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
results = (string)e.Result;
}
,然後我把它用:
string result1 = ExecuteCommandSync(command);
你需要給我們更多的上下文 - 你在WinForms應用程序,WPF,服務器端運行這個嗎? – 2012-01-12 12:03:26
你想在這裏做什麼? – 2012-01-12 12:04:10
在另一個線程中運行代碼不會減少運行該代碼所需的時間。它只會帶來更好的用戶體驗,因爲程序不會掛起。 – 2012-01-12 12:04:14