На самом деле .NET Framework и Windows довольно хорошо управляют потоками, равномерно распределяя их по каждому процессору. Однако распределением потоков можно манипулировать вручную, используя Process
и ProcessThread
.
using System;
using System.Diagnostics;
using System.Threading;
namespace ThreadTest
{
class Program
{
static void Main(string[] args)
{
//Get the our application's process.
Process process = Process.GetCurrentProcess();
//Get the processor count of our machine.
int cpuCount = Environment.ProcessorCount;
Console.WriteLine("CPU Count : {0}", cpuCount);
//Since the application starts with a few threads, we have to
//record the offset.
int offset = process.Threads.Count;
Thread[] threads = new Thread[cpuCount];
Console.WriteLine(process.Threads.Count);
LogThreadIds(process);
//Create and start a number of threads that equals to
//our processor count.
for (int i = 0; i < cpuCount; ++i)
{
Thread t = new Thread(new ThreadStart(Calculation))
{ IsBackground = true };
t.Start();
}
//Refresh the process information in order to get the newest
//thread list.
process.Refresh();
Console.WriteLine(process.Threads.Count);
LogThreadIds(process);
//Set the affinity of newly created threads.
for (int i = 0; i < cpuCount; ++i)
{
//process.Threads[i + offset].ProcessorAffinity = (IntPtr)(1L << i);
//The code above distributes threads evenly on all processors.
//But now we are making a test, so let's bind all the threads to the
//second processor.
process.Threads[i + offset].ProcessorAffinity = (IntPtr)(1L << 1);
}
Console.ReadLine();
}
static void Calculation()
{
//some extreme loads.
while (true)
{
Random rand = new Random();
double a = rand.NextDouble();
a = Math.Sin(Math.Sin(a));
}
}
static void LogThreadIds(Process proc)
{
//This will log out all the thread id binded to the process.
//It is used to test whether newly added threads are the latest elements
//in the collection.
Console.WriteLine("===Thread Ids===");
for (int i = 0; i < proc.Threads.Count; ++i)
{
Console.WriteLine(proc.Threads[i].Id);
}
Console.WriteLine("===End of Thread Ids===");
}
}
}
Теперь проверьте диспетчер задач, мы видим, что второй процессор принимает на себя все рабочие нагрузки. Окно диспетчера задач
Я думал, что опубликую другое решение, которое нашел, я обновил это решение, добавив в него файл журнала.
Это похоже на Публикация веб-приложения из командной строки , но только что вычищен и добавлен файл журнала. также проверьте оригинальный источник http://www.digitallycreated.net/Blog/59/locally-publishing-a-vs2010-asp.net-web-application-using-msbuild
Создайте MSBuild_publish_site.bat (назовите его как угодно) в корне проекта веб-приложения
set msBuildDir=%WINDIR%\Microsoft.NET\Framework\v4.0.30319
set destPath=C:\Publish\MyWebBasedApp\
:: clear existing publish folder
RD /S /Q "%destPath%"
call %msBuildDir%\msbuild.exe MyWebBasedApp.csproj "/p:Configuration=Debug;PublishDestination=%destPath%;AutoParameterizationWebConfigConnectionStrings=False" /t:PublishToFileSystem /l:FileLogger,Microsoft.Build.Engine;logfile=Manual_MSBuild_Publish_LOG.log
set msBuildDir=
set destPath=
Обновите файл проекта веб-приложения MyWebBasedApp.csproj, добавив следующий XML-файл под тегом <Import Project=
<Target Name="PublishToFileSystem" DependsOnTargets="PipelinePreDeployCopyAllFilesToOneFolder">
<Error Condition="'$(PublishDestination)'==''" Text="The PublishDestination property must be set to the intended publishing destination." />
<MakeDir Condition="!Exists($(PublishDestination))" Directories="$(PublishDestination)" />
<ItemGroup>
<PublishFiles Include="$(_PackageTempDir)\**\*.*" />
</ItemGroup>
<Copy SourceFiles="@(PublishFiles)" DestinationFiles="@(PublishFiles->'$(PublishDestination)\%(RecursiveDir)%(Filename)%(Extension)')" SkipUnchangedFiles="True" />
</Target>
это работает лучше для меня, чем другие решения.
Проверьте следующее для получения дополнительной информации:
Полный файл msbuild с вдохновением от CubanX
<Project ToolsVersion="3.5" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Target Name="Publish">
<RemoveDir Directories="..\build\Release\Web\"
ContinueOnError="true" />
<MSBuild Projects="TheWebSite.csproj"
Targets="ResolveReferences;_CopyWebApplication"
Properties="Configuration=Release;WebProjectOutputDir=..\build\Release\Web;OutDir=..\build\Release\Web\bin\"
/>
</Target>
<Target
Name="Build"
DependsOnTargets="Publish;">
</Target>
</Project>
. Здесь размещается опубликованный веб-сайт в папке .. \ build \ Release
.