我有一个程序进行内存密集型模拟.下面我写了一个小型控制台应用程序,它复制了我遇到的问题.
class Program {
static void Main(string[] args) {
var t = new Task(() => DoMemoryHog(20000000));
t.Start();
t.Wait();
t.Dispose();
t = null;
GC.Collect();
Console.WriteLine("Done");
Console.ReadLine();
}
static void DoMemoryHog(int n) {
ConcurrentBag<double> results = new ConcurrentBag<double>();
Parallel.For(0, n, (i) => {
results.Add(Math.Sqrt(i.GetHashCode()));
});
}
}
Run Code Online (Sandbox Code Playgroud)
当我运行程序时,我可以看到Windows任务管理器中使用的内存量增加,但是当任务完成(并显示"完成")时,内存不会恢复到原始级别,只会发生当我关闭应用程序时.
有没有人知道如何释放并行任务使用的内存,而主应用程序一直在运行?正如你所看到的,我已经尝试过处理它,将它的引用设置为null并手动运行垃圾收集器(我知道你不应该这样做).
如何执行System.Threading.Task作为两个或更多其他任务结果的延续?
public Task<FinalResult> RunStepsAsync()
{
Task<Step1Result> task1 = Task<Step1Result>.Factory.StartNew(Step1);
// Use the result of step 1 in steps 2A and 2B
Task<Step2AResult> task2A = task1.ContinueWith(t1 => Step2A(t1.Result));
Task<Step2BResult> task2B = task1.ContinueWith(t1 => Step2B(t1.Result));
// Now merge the results of steps 2A and 2B in step 3
Task<FinalResult> task3 = task2A
.ContinueWith(
t2A => task2B.ContinueWith(
t2B => Step3(t2A.Result, t2B.Result)))
.Unwrap();
return task3;
}
Run Code Online (Sandbox Code Playgroud)
这样可行,但是双重ContinueWith似乎效率低下.有没有更好的方法来实现这一点,也许使用TaskCompletionSource?(我不想使用锁或Task.WaitAll.)
我正在研究一个模拟系统,除其他外,它允许在离散的模拟时间步骤中执行任务.执行都发生在模拟线程的上下文中,但是,从使用系统的"操作员"的角度来看,它们希望表现为异步.值得庆幸的是,TPL具有方便的'async/await'关键字,这使得它非常简单.我在模拟上有一个原始方法,如下所示:
public Task CycleExecutedEvent()
{
lock (_cycleExecutedBroker)
{
if (!IsRunning) throw new TaskCanceledException("Simulation has been stopped");
return _cycleExecutedBroker.RegisterForCompletion(CycleExecutedEventName);
}
}
Run Code Online (Sandbox Code Playgroud)
这基本上是创建一个新的TaskCompletionSource然后返回一个Task.此任务的目的是在模拟发生新的"ExecuteCycle"时执行其继续.
然后我有一些像这样的扩展方法:
public static async Task WaitForDuration(this ISimulation simulation, double duration)
{
double startTime = simulation.CurrentSimulatedTime;
do
{
await simulation.CycleExecutedEvent();
} while ((simulation.CurrentSimulatedTime - startTime) < duration);
}
public static async Task WaitForCondition(this ISimulation simulation, Func<bool> condition)
{
do
{
await simulation.CycleExecutedEvent();
} while (!condition());
}
Run Code Online (Sandbox Code Playgroud)
这些非常方便,从"运营商"角度构建序列,根据条件采取行动并等待模拟时间段.我遇到的问题是CycleExecuted非常频繁地发生(如果我以完全加速的速度运行,大约每隔几毫秒).因为这些'wait'辅助方法在每个循环中注册一个新的'await',这会导致TaskCompletionSource实例中的大量转换.
我已经分析了我的代码,并且我发现大约5.5%的总CPU时间花费在这些完成中,其中"活动"代码中只花费了可忽略不计的百分比.实际上,所有时间都花在注册新的完成上,同时等待触发条件有效.
我的问题:我如何在保持async/await模式的便利性的同时提高写入"操作员行为"的性能?我认为我需要像轻量级和/或可重复使用的TaskCompletionSource这样的东西,因为触发事件经常发生.
我一直在做更多的研究,听起来一个很好的选择是创建Awaitable模式的自定义实现,它可以直接绑定到事件,消除了对一堆TaskCompletionSource和Task实例的需要.它在这里有用的原因是有很多不同的延续等待CycleExecutedEvent,他们需要经常等待它.理想情况下,我正在寻找一种方法来排队延续回调,然后在事件发生时回调队列中的所有内容.我会继续挖掘,但如果人们知道一个干净的方法,我欢迎任何帮助.
对于将来浏览这个问题的人来说,这是我放在一起的定制等待者:
public sealed class CycleExecutedAwaiter : INotifyCompletion
{
private readonly …Run Code Online (Sandbox Code Playgroud) 我在C#,VS2012,WPF 4.5中有以下代码.我的期望是,.ContinueWith将在任务完成后执行(这是一个延续的完整目的,不是吗?).
这应该导致值为2英寸finalResult.
int myTestInt = 0;
Task task = Task.Factory.StartNew(async () =>
{
myTestInt = 1;
await Task.Delay(TimeSpan.FromSeconds(6));
myTestInt = 2;
}).ContinueWith(_ =>
{
int finalResult = myTestInt;
});
Run Code Online (Sandbox Code Playgroud)
实际上,finalResult被赋值为1.所以似乎await已经在声明中开始了延续.
这是预期的行为吗?我在这里错过了什么吗?ContinueWith任务完成后我不能依靠启动吗?
更新:
Justin的回答激发了我检查以下内容:
int myTestInt = 0;
Task task=Task.Factory.StartNew(async () =>
{
myTestInt = 1;
await Task.Delay(TimeSpan.FromSeconds(6));
myTestInt = 2;
});
task.Wait();
int result2 = myTestInt;
Run Code Online (Sandbox Code Playgroud)
finalResult仍设置为1.是否无法可靠地等待包含awaits 的任务完成?
这是启动多个任务的示例代码
Task.Factory.StartNew(() =>
{
//foreach (KeyValuePair<string, string> entry in dicList)
Parallel.ForEach(dicList,
entry =>
{
//create and add the Progress in UI thread
var ucProgress = (Progress)fpPanel.Invoke(createProgress, entry);
//execute ucProgress.Process(); in non-UI thread in parallel.
//the .Process(); must update UI by using *Invoke
ucProgress.Process();
System.Threading.Thread.SpinWait(5000000);
});
});
.ContinueWith(task =>
{
//to handle exceptions use task.Exception member
var progressBar = (ProgressBar)task.AsyncState;
if (!task.IsCancelled)
{
//hide progress bar here and reset pb.Value = 0
}
},
TaskScheduler.FromCurrentSynchronizationContext() //update UI from UI thread
); …Run Code Online (Sandbox Code Playgroud) 在使用数据流后,我遇到了一个新问题.我想限制所有块的输入队列.我的产品块(ActionBlock)正在快速创建5000个元素并将它们发布到广播块.因此,如果我将广播块的BoundedCapacity设置为100,则会抛出大量数据.但是我希望生产块等待我的缓冲区输入队列中的新槽.
有没有办法摆脱这个问题?
在C#TPL数据流库中,SingleProducerConstrained是ActionBlocks的优化选项,当只有一个线程为动作块提供时,您可以使用它:
如果一个块只曾经打算通过一次单一的生产商,同时意味着只有一个线程被用来将使用类似帖子,OfferMessage和方法的块上完成的,这个属性可以被设置为true通知阻止它不需要应用额外的同步.
如果有什么的ActionBlock使用具有单个TransformBlock喂MaxDegreeOfPArallelism> 1 - 将违反规则的ActionBlock SingleProcerContrained设置为true?或者是MaxDegreeOfPArallelism> 1的单个TransformBlock仍被视为"单一生产者"?
我有以下示例:(请同时阅读代码中的注释,因为它会更有意义)
public async Task<Task<Result>> MyAsyncMethod()
{
Task<Result> resultTask = await _mySender.PostAsync();
return resultTask;
// in real-life case this returns to a different assembly which I can't change
// but I need to do some exception handling on the Result in here
}
Run Code Online (Sandbox Code Playgroud)
让我们假设PostAsync_ 的方法mySender 如下:
public Task<Task<Result>> PostAsync()
{
Task<Result> result = GetSomeTask();
return result;
}
Run Code Online (Sandbox Code Playgroud)
问题是:
因为我不期待在实际Result中MyAsyncMethod,如果PostAsync方法抛出一个异常,在这种情况下会异常被抛出和处理?
和
有什么方法可以处理我的程序集中的异常吗?
当我试图改为时,我感到很惊讶MyAsyncMethod:
public async Task<Task<Result>> MyAsyncMethod()
{
try
{
Task<Result> …Run Code Online (Sandbox Code Playgroud) 对于发送到服务器的每个调用,我创建一个新的计时器Task.Delay来监视它的超时.
假设会有数百个并发呼叫.因此会有数百个Task计数器计时器.
我想TPL的内部实现考虑了这个场合,所有的任务都依赖于相同的底层计时器?
我不太了解Task.Delay内部工作的机制.
Parallel.ForEach我的Windows服务中有代码.如果ParallelOptions.MaxDegreeOfParallelism设置为-1,我正在使用我的大部分CPU.然而,停止服务持续半分钟.应该接收服务应该停止的信号的某些内部控制器线程会超出处理器时间.我将进程优先级设置为低于正常值,但这可能是不相关的信息.
即使所有线程都忙,我还能做些什么来缩短停止服务的时间?
我正在试图暂时降低线程池中线程的优先级,因为我没有任何异步代码,但Internet说这是一个坏主意,所以在这里要求"正确"的方式.
螺纹(包括操作系统和.NET)在所有情况下之间的不同OnStart和OnStop.此外,如果停止时间非常长,那么OnStop有时最终将调用的OS线程是一个新线程,而不是在日志中更早显示.
要构建此代码,请创建新的Windows服务项目,从设计器添加ProjectInstaller类,将Account更改为LocalService,然后使用InstallUtil安装一次.确保LocalService可以写入C:\ Temp.
public partial class Service1 : ServiceBase
{
private ManualResetEvent stopEvent = new ManualResetEvent(false);
private Task mainTask;
private StreamWriter writer = File.AppendText(@"C:\Temp\Log.txt");
public Service1()
{
InitializeComponent();
writer.AutoFlush = true;
}
protected override void OnStart(string[] args)
{
Log("--------------");
Log("OnStart");
mainTask = Task.Run(new Action(Run));
}
protected override void OnStop()
{
Log("OnStop");
stopEvent.Set();
mainTask.Wait();
Log("--------------");
}
private void Log(string line)
{
writer.WriteLine(String.Format("{0:yyyy-MM-dd HH:mm:ss.fff}: [{1,2}] {2}",
DateTime.Now, Thread.CurrentThread.ManagedThreadId, line));
} …Run Code Online (Sandbox Code Playgroud)