我有一个带有简单Web服务的ASP.NET 4.0 WebForms页面WebMethod.此方法用作异步/ TPL代码的同步包装器.我面临的问题是,内部Task有时会有一个null SynchronizationContext(我的偏好),但有时会有一个同步上下文System.Web.LegacyAspNetSynchronizationContext.在我提供的示例中,这并不会导致问题,但在我的实际开发场景中可能会导致死锁.
对服务的第一次调用似乎总是使用空同步上下文运行,接下来的几个也可能.但是一些快速激活的请求会开始弹出ASP.NET同步上下文.
[WebMethod]
public static string MyWebMethod(string name)
{
var rnd = new Random();
int eventId = rnd.Next();
TaskHolder holder = new TaskHolder(eventId);
System.Diagnostics.Debug.WriteLine("Event Id: {0}. Web method thread Id: {1}",
eventId,
Thread.CurrentThread.ManagedThreadId);
var taskResult = Task.Factory.StartNew(
function: () => holder.SampleTask().Result,
creationOptions: TaskCreationOptions.None,
cancellationToken: System.Threading.CancellationToken.None,
scheduler: TaskScheduler.Default)
.Result;
return "Hello " + name + ", result is " + taskResult;
}
Run Code Online (Sandbox Code Playgroud)
存在的定义TaskHolder:
public class TaskHolder …Run Code Online (Sandbox Code Playgroud) asp.net synchronizationcontext task-parallel-library webmethod async-await
我正在编写一个消耗资源的库,无论出于什么原因,API的设计方式是在不同的线程上引发事件,但是必须在主线程上完成API的调用.
假设我尝试使用的API被定义为(我将省略事件定义):
public sealed class DodgyService
{
public void MethodThatHasToBeCalledOnTheMainThread() { ... }
}
Run Code Online (Sandbox Code Playgroud)
为了使用这个API,我在我的库中添加了一个名为Service(Yup,非常原始名称)的服务,它将创建一个新任务(当我指定一个已经创建的TaskScheduler时,它将在主线程上运行SynchronizationContext).
这是我的实现:
public class Service
{
private readonly TaskFactory _taskFactory;
private readonly TaskScheduler _mainThreadScheduler;
public Service(TaskFactory taskFactory, TaskScheduler mainThreadScheduler)
{
_taskFactory = taskFactory;
_mainThreadScheduler = mainThreadScheduler;
}
// Assume this method can be called from any thread.
// In this sample is called by the main thread but most of the time
// the caller will be running on a background thread.
public Task …Run Code Online (Sandbox Code Playgroud) 我有一个名为Load的UI按钮.它产生一个线程,反过来产生一个任务.任务等待,如果过期,任务将被取消."加载"按钮未禁用,用户可以多次单击它.每次单击时,都应取消上一个任务.
我对如何在这里使用CancellationTokenSource和CancellationToken感到困惑.下面是代码.您能否建议如何使用它以及以下用法是否有任何问题?请不要异步,因为我们还没有.
CancellationTokenSource _source = new CancellationTokenSource();
public void OnLoad()
{
//Does this cancel the previously spawned task?
_source.Cancel();
_source.Dispose();
_source = new CancellationTokenSource();
var activeToken = _source.Token;
//Do I need to do the above all the time or is there an efficient way?
Task.Factory.StartNew(() =>
{
var child = Task.Factory.StartNew(() =>
{
Thread.Sleep(TimeSpan.FromSeconds(20));
activeToken.ThrowIfCancellationRequested();
}, activeToken);
if (!child.Wait(TimeSpan.FromSeconds(5)))
{
_source.Cancel();
}
});
}
Run Code Online (Sandbox Code Playgroud)
注意我需要取消任何以前生成的任务,并且每个生成的任务都应该超时.
在实现返回关于抛出异常的Task的方法时,是否存在MS"最佳实践"或合同协议?这是在编写单元测试时出现的,我试图弄清楚我是否应该测试/处理这种情况(我认识到答案可能是"防御性编码",但我不希望这是答案).
即
方法必须始终返回一个Task,该Task应该包含抛出的Exception.
方法必须始终返回一个Task,除非该方法提供无效参数(即ArgumentException).
方法必须始终返回一个任务,除非开发人员变得流氓并做他/她想要的事情(jk).
Task Foo1Async(string id){
if(id == null){
throw new ArgumentNullException();
}
// do stuff
}
Task Foo2Async(string id){
if(id == null){
var source = new TaskCompletionSource<bool>();
source.SetException(new ArgumentNullException());
return source.Task;
}
// do stuff
}
Task Bar(string id){
// argument checking
if(id == null) throw new ArgumentNullException("id")
try{
return this.SomeService.GetAsync(id).ContinueWith(t => {
// checking for Fault state here
// pass exception through.
})
}catch(Exception ex){
// handling more Fault state here.
// defensive code.
// return …Run Code Online (Sandbox Code Playgroud) 所以这是我的代码
Task<int[]> parent = Task.Run(() =>
{
var result = new int[3];
TaskFactory tf = new TaskFactory(TaskCreationOptions.AttachedToParent, TaskContinuationOptions.ExecuteSynchronously);
for (int i = 0; i < result.Length; i++)
{
int j = i;
tf.StartNew(() => result[j] = GetRandomNumber(j));
}
return result;
});
var finalTask = parent.ContinueWith(parentTask =>
{
foreach (var i in parentTask.Result)
{
Console.WriteLine(i);
}
});
finalTask.Wait();
Run Code Online (Sandbox Code Playgroud)
基本上我创建3 Tasks,这是Task被叫父母的孩子(我猜).我要求父任务等待所有三个子任务完成.之后,由于finalTask这种状态,将等待执行finalTask.Wait();.但事情并没有像预期的那样发生.我的意思是应用程序在任何GetRandomNumber调用完成之前退出.这里的代码的某些部分是从书中复制的,该书表明那些父任务应该等待子任务完成,这显然没有发生.我在这里错过了什么吗?
这就是GetRandomNumber所做的
public static int GetRandomNumber(int ii)
{
Random rand = new Random(); …Run Code Online (Sandbox Code Playgroud) 我试图在多线程环境中更新进度条.我知道很多问题已经解决了这个问题,但提议的解决方案都没有对我有用.这是我的代码的主干:
public static void DO_Computation(//parameters) {
//Intialisation of parameters
Parallel.For(struct initialisation with local data) {
//business logic
//Call to update_progressbar (located in an another class, as the DO_Computation function is in Computation.cs class (not deriving from Form).
WinForm.Invoke((Action)delegate {Update_Progress_Bar(i);}); //WinForm is a class that exposes the progressbar.
}
}
Run Code Online (Sandbox Code Playgroud)
这是行不通的(当达到100%时,进度条会冻结,这是正常的(我们可以参考这篇文章中的微软文章(实际上,这不是一种线程安全的操作方法).)Microsoft网站用于包装所述Parallel.For环成Task例程如下:
public static void DO_Computation(//parameters) {
//Intialisation of parameters
Task.Factory.StartNew(() =>
{
Parallel.For(struct initialosation with local data) {
//business logic
//Call to update_progressbar …Run Code Online (Sandbox Code Playgroud) 我目前正试图找到Akka.NET的消息调度程序中的瓶颈(java/scala actor模型框架的端口)对于那些感兴趣的人,可以在这里找到:https://github.com/akkadotnet/akka.net
我们似乎可以扩展到8核,到目前为止一切似乎都很好.但是,当在较大的机器上运行时,一切都会最终崩溃.我们已经在16核计算机上测试了它,它可以很好地扩展到某个点,然后突然,消息吞吐量减半.
这张图片是在我的笔记本电脑上进行分析
请参阅:http://i.stack.imgur.com/DxboR.png获取完整图像
.瓶颈是Task.Factory.StartNew,还是ConcurrentQueue.Enqueue?我不确定我是否正确阅读了这些数字.
以下是我们的邮件调度程序和邮箱如何工作的简要说明:
邮件发布到邮箱后,邮箱会检查邮箱当前是否正在处理邮件.如果它正在处理消息,它只是让当前运行的Task消耗新消息.
基本上,我们将一条消息发布到ConcurrentQueue,当前的邮箱运行将找到它.
如果邮件在发布邮件时当前处于空闲状态,那么我们将使用邮箱计划Task.Factory.StartNew(mailboxAction).
为了确保在任何给定时间只有一个任务针对特定邮箱运行,我们使用Interlocked检查来查看邮箱是忙还是空闲.互锁检查有效,这已经过广泛测试,因此我们知道我们不会为同一个邮箱启动多个任务.
有什么想法可能导致吞吐量完全打破16核心机器?在较小的机器上不会发生相同的效果,当它们无法再扩展时,它们在最大吞吐量时保持稳定.
我在16核心机器上验证的一件事是,邮箱似乎处理得太快,耗尽了actor消息队列中的所有消息,这将在新消息到达时引导邮箱的新调度.也就是说,消费者比生产者更快.
我想知道.如何删除块之间的链接?换一种说法.我想与LinkTo相反.
我想写一个基于tlp数据流的记录器.
我编写了这个接口,并希望在需要时删除ILogListener的订阅.
public interface ILogManager
{
void RemoveListener(ILogListener listener);
}
Run Code Online (Sandbox Code Playgroud) 我有这个代码处理的Web请求;
Response = await Client.SendAsync(Message, HttpCompletionOption.ResponseHeadersRead, CToken);
Run Code Online (Sandbox Code Playgroud)
在读取响应头之后和内容完成读取之前返回.当我打电话给这一行来获取内容时......
return await Response.Content.ReadAsStringAsync();
Run Code Online (Sandbox Code Playgroud)
我希望能在X秒后停止它.但它不接受取消令牌.
我需要做这样的工作:
由于我需要控制并行处理的页数,我决定使用TPL数据流:
____________________________
| Data pipe |
| BufferBlock<Page> |
| BoundedCapacity = 1 |
|____________________________|
|
____________________________
| Process images |
| TransformBlock<Page, Page> |
| BoundedCapacity = 1 |
| MaxDegreeOfParallelism = 8 |
|____________________________|
|
____________________________
| Save page |
| ActionBlock<Page> |
| BoundedCapacity = 1 |
| MaxDegreeOfParallelism = 5 |
|____________________________|
Run Code Online (Sandbox Code Playgroud)
现在我需要"过程图像"来并行处理图像,但我想限制我在当前工作中所有并行页面上处理的图像数量.
我可以将TrasnformManyBlock用于"过程图像",但如何在"保存页面"块中将它们收回?
____________________________
| Data pipe |
| BufferBlock<Page> |
| BoundedCapacity = 1 |
|____________________________|
|
___________________________________
| Load …Run Code Online (Sandbox Code Playgroud) c# ×9
.net ×5
async-await ×3
tpl-dataflow ×2
akka.net ×1
asp.net ×1
asynchronous ×1
c#-4.0 ×1
exception ×1
httpclient ×1
webmethod ×1