我是一名初級程序員,我試圖解決一個任務。使用c#.net 4.0我正在運行文件夾,選擇所有* .xml文件,並將每個文件寫入具有新擴展名* .bin的新文件夾。對於每個文件在寫之前我正在應用算法,這是由另一個程序員編寫的,我不知道它的實現。如何使用類任務進行並行處理
所以我讀* .xml文件,反序列化並將其寫入新的* .bin文件。當我沒有使用並行編程時,對於2000個文件我有1分鐘的時間。現在我決定使用並行編程任務。現在我爲每個文件創建新的任務(所有進程(讀取 - 反序列化 - 寫入)在一個任務中),現在我有40秒。但我認爲並行編程幫助我將時間縮短到25-30秒。
請給我你的評論我做錯了什麼,以及我如何去實現這一點。謝謝。
byte[] buffer;
using (Stream stream = new FileInfo(file).OpenRead())
{
buffer = new byte[stream.Length];
stream.Read(buffer, 0, (int)stream.Length);
}
foreach (var culture in supportedCultures)
{
CultureInfo currentCulture = culture;
Tasks.Add(Task.Factory.StartNew(() =>
{
var memoryStream = new MemoryStream(buffer);
Task<object> serializeTask = Task.Factory.StartNew(() =>
{
return typesManager.Load(memoryStream, currentCulture);
}, TaskCreationOptions.AttachedToParent);
string currentOutputDirectory = null;
if (outputDirectory != null)
{
currentOutputDirectory = outputDirectory.Replace(PlaceForCultureInFolderPath,
currentCulture
.ToString());
Directory.CreateDirectory(currentOutputDirectory);
}
string binFile = Path.ChangeExtension(Path.GetFileName(file), ".bin");
string binPath = Path.Combine(
currentOutputDirectory ?? Path.GetDirectoryName(file),
binFile);
using (FileStream outputStream = File.OpenWrite(binPath))
{
try
{
new BinaryFormatter().Serialize(outputStream,serializeTask.Result);
}
catch (SerializationException e)
{
ReportCompilationError(e.Message, null);
}
}
}));
}
請提供一些代碼 –