我正在开发一个创建数十万个硬链接(这是应用程序的核心功能)的应用程序。在托管代码中创建硬链接
我使用了dotNET 4.0现在提供的并行编程功能。这工作得很好。请参阅下面的示例snippits。
或者:
Parallel.For(from, until, delegate(int i)
{
j += 1;
fileIndex = Convert.ToInt32(Math.Round(j * 0.001) + 1);
//determine the hardlink files; we have to have an unique name for the hardlink for each individual hardlink
fileName = fiArray[fileIndex].Name; //Path.GetFileNameWithoutExtension(textBoxFile.Text);
destinationFileName = Path.Combine(textBoxDestination.Text, string.Concat(fileName, "_", i.ToString(), ".txt"));
fr.CreateHardLink(destinationFileName, fiArray[fileIndex].FullName);
});
或者:
//loop that does the actual work
for (int i = 0; i < nudThreads.Value; i++)
{
//determine the work package per task
from = 0 + until + 1;
until = (i * (Convert.ToInt32(HardLinks/ThreadNo))) + 1;
var compute = Task.Factory.StartNew(() =>
{
token.ThrowIfCancellationRequested(); //uit boek
return Work(from, until, false);//todo: counter moet nog worden meegenomen
}, tokenSource.Token);
tasks.Add(compute);
var displayResults = compute.ContinueWith(resultTask => UpdateControls(),
CancellationToken.None,
TaskContinuationOptions.OnlyOnRanToCompletion,
ui);
CheckedListBoxFiles.Items.Add(DateTime.Now.ToString() + " : Created the hardlinks for: " + displayResults + " files.");
Application.DoEvents();
var displayCancelledTasks = compute.ContinueWith(resultTask => UpdateControls(),
CancellationToken.None,
TaskContinuationOptions.OnlyOnCanceled, ui);
CheckedListBoxFiles.Items.Add(DateTime.Now.ToString() + " : Cancelled a task at: " + displayCancelledTasks + " files.");
Application.DoEvents();
}
的问题我已经是这样的:CreateHardlink是Kernel32.dll中的一部分,因此运行在非托管代码。我所知道的并行ctp是并行任务必须以托管代码运行。 是否有可用于createhardlink的托管替代方案?有谁知道如何在托管代码中创建硬链接,并且没有人有关于并行编程和使用非托管代码的任何提示吗?
只是一个小纸条...我意识到这可能不是你所有的代码,但以防万一:你在并行上下文中设置fileIndex,fileName和destinationFileName,但它似乎是在上下文之外定义的。这会导致难以检测到的竞争状况 - 如果在kernel32调用之后没有检查错误代码,这几乎是不可能的。 – 2011-04-29 19:02:15