标签: task-parallel-library

如何强制取消任务?

假设,有一项任务包含以下约:

Task someTask = new Task(() => {

  while(!IsCancellationRequested) {

    Do_something_over_a_long_period_of_time();
    token.ThrowIfCancellationRequested();

    Do_something_over_a_long_period_of_time();
    token.ThrowIfCancellationRequested();

    Do_something_over_a_long_period_of_time();
    token.ThrowIfCancellationRequested();
  }
});
someTask.Start();
Run Code Online (Sandbox Code Playgroud)

并且有非常不耐烦的用户.他们渴望立即终止我的申请.他们不想等待长时间的行动.

我以前使用Thread该类,并能够通过调用Abort()命令立即中止我的所有线程.

我如何立即中止我的任务?

谢谢.

c# multithreading task task-parallel-library

9
推荐指数
2
解决办法
1万
查看次数

在监听消耗IEnumerable <T>时,Blocking.Peek()的类似于BlockingCollection

我正在使用Pipelines模式实现来将消费者与生产者分离,以避免消费者的慢速问题.

如果在消息处理阶段出现任何异常,[1]它将丢失并且不会分派给其他服务/层[2].如何在[3]这样的消息中处理这样的问题不会丢失,重要的是什么!消息的顺序不会混淆,所以上层服务/层将按照它们进入的顺序获取消息.我有一个想法涉及另一个中间Queue但看起来很复杂?不幸的是BlockingCollection<T>,没有公开任何类比的Queue.Peek()方法,所以我可以只读取下一个可用的消息,并在成功处理的情况下做Dequeue()

private BlockingCollection<IMessage> messagesQueue;    

// TPL Task does following:
// Listen to new messages and as soon as any comes in - process it
foreach (var cachedMessage in 
             messagesQueue.GetConsumingEnumerable(cancellation))
{    
    const int maxRetries = 3;
    int retriesCounter = 0;
    bool isSent = false;

    // On this point a message already is removed from messagesQueue
    while (!isSent && retriesCounter++ <= maxRetries)
    {
        try
        {
           // …
Run Code Online (Sandbox Code Playgroud)

c# wcf multithreading .net-4.0 task-parallel-library

9
推荐指数
1
解决办法
5717
查看次数

使用async/await并从ASP.NET Web API方法返回Task <HttpResponseMessage>

我有一个像这样的可移植类库(PCL)方法:

public async Task<string> GetLineStatuses()
{
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
    using (HttpWebResponse response = (HttpWebResponse)await request.GetResponseAsync())
    {
        return response.GetResponseStream().ReadAllText();
    }
}
Run Code Online (Sandbox Code Playgroud)

我的ASP.NET Web Api方法如下所示:

public async Task<HttpResponseMessage> Get()
{
    HttpResponseMessage response = new HttpResponseMessage();
    string statuses = await service.GetStatuses();
    response.Content = new StringContent(statuses);
    return response;
}
Run Code Online (Sandbox Code Playgroud)

在Web API中返回Task有什么含义.这是允许的吗?我想使用await的唯一原因是我可以使用可移植类库(PCL).什么是最佳做法?我应该有我的方法的同步版本和异步版本吗?什么是性能和代码可读性和可维护性含义?

如果我回来Task<string>而不是,我也会有同样的效果Task<HttpResponseMessage>吗?

.net c# task-parallel-library async-await asp.net-web-api

9
推荐指数
1
解决办法
2万
查看次数

如何从.NET 4.5中的并行任务中获益

我想使用.NET迭代器和并行Tasks/await?.像这样的东西:

IEnumerable<TDst> Foo<TSrc, TDest>(IEnumerable<TSrc> source)
{
    Parallel.ForEach(
        source,
        s=>
        {
            // Ordering is NOT important
            // items can be yielded as soon as they are done                
            yield return ExecuteOrDownloadSomething(s);
        }
}
Run Code Online (Sandbox Code Playgroud)

不幸的是.NET无法原生地处理这个问题.到目前为止@svick的最佳答案 - 使用AsParallel().

奖励:任何实现多个发布者和单个订阅者的简单异步/等待代码?订阅者将屈服,并且pubs将处理.(仅核心库)

c# yield-return task-parallel-library async-await c#-5.0

9
推荐指数
1
解决办法
4336
查看次数

防止任务在某个线程上运行

我一直在努力与一些异步等待的东西.我正在使用RabbitMQ在某些程序之间发送/接收消息.

作为一个背景,RabbitMQ客户端使用我可以看到的3个左右的线程:一个连接线程和两个心跳线程.每当通过TCP接收消息时,连接线程就会处理它并调用我通过接口提供的回调.文档说最好避免在这个调用期间做很多工作,因为它在与连接相同的线程上完成并且事情需要继续.它们提供了一个QueueingBasicConsumer具有阻塞'Dequeue'方法的方法,该方法用于等待接收消息.

我希望我的消费者能够在这个等待时间内实际释放他们的线程上下文,以便其他人可以做一些工作,所以我决定使用async/await任务.我写了一个以下列方式AwaitableBasicConsumer使用TaskCompletionSources 的类:

我有一个等待的Dequeue方法:

public Task<RabbitMQ.Client.Events.BasicDeliverEventArgs> DequeueAsync(CancellationToken cancellationToken)
{
    //we are enqueueing a TCS. This is a "read"
    rwLock.EnterReadLock();

    try
    {
        TaskCompletionSource<RabbitMQ.Client.Events.BasicDeliverEventArgs> tcs = new TaskCompletionSource<RabbitMQ.Client.Events.BasicDeliverEventArgs>();

        //if we are cancelled before we finish, this will cause the tcs to become cancelled
        cancellationToken.Register(() =>
        {
            tcs.TrySetCanceled();
        });

        //if there is something in the undelivered queue, the task will be immediately completed
        //otherwise, we queue the task into deliveryTCS
        if (!TryDeliverUndelivered(tcs))
            deliveryTCS.Enqueue(tcs);
        }

        return tcs.Task; …
Run Code Online (Sandbox Code Playgroud)

c# multithreading asynchronous rabbitmq task-parallel-library

9
推荐指数
1
解决办法
1355
查看次数

IEnumerable <T>,Parallel.ForEach和Memory Management

我正在阅读和处理大量的Sql Server数据(数百万行中有10行,100多万行+行).在每个源行上执行的处理很重要.单线程版本没有达到预期效果.我目前的并行处理版本在一些较小的批次(300,000个源行,1M个输出行)上表现非常好,但是我遇到了一些非常大的运行的Out of Memory异常.

代码受到了这里提供的答案的启发: 有没有办法将任务并行库(TPL)与SQLDataReader一起使用?

这是一般的想法:

获取源数据(数据太大而无法读入内存,因此我们将"流式传输")

public static IEnumerable<MyObject> ReadData()
{
    using (SqlConnection con = new SqlConnection(Settings.ConnectionString)) 
       using (SqlCommand cmd = new SqlCommand(selectionSql, con))
       {
            con.Open();
            using (SqlDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection))
            {
            while (dr.Read())
            {
                // make some decisions here – 1 to n source rows are used
                // to create an instance of MyObject
                yield return new MyObject(some parameters);
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

一旦我们到达并行处理点,我们希望使用SqlBulkCopy对象来写入数据.因此,我们不希望并行处理单个MyObjects,因为我们希望每个线程执行批量复制.因此,我们将从上面读取另一个返回"批量"MyObjects的IEnumerable

class MyObjectBatch 
{
    public List<MyObject> Items { get; set; }

    public MyObjectBatch (List<MyObject> …
Run Code Online (Sandbox Code Playgroud)

c# sql-server memory-management task-parallel-library

9
推荐指数
1
解决办法
1838
查看次数

立即从异步方法投掷

从方法抛出的异常的正常行为async Task是保持休眠状态,直到稍后观察它们,或者直到任务被垃圾收集.

我可以想到我可能想立即投掷的情况.这是一个例子:

public static async Task TestExAsync(string filename)
{
    // the file is missing, but it may be there again
    // when the exception gets observed 5 seconds later,
    // hard to debug

    if (!System.IO.File.Exists(filename))
        throw new System.IO.FileNotFoundException(filename);

    await Task.Delay(1000);
}

public static void Main()
{
    var task = TestExAsync("filename");
    try
    {
        Thread.Sleep(5000); // do other work
        task.Wait(); // wait and observe
    }
    catch (AggregateException ex)
    {
        Console.WriteLine(new { ex.InnerException.Message, task.IsCanceled });
    }
    Console.ReadLine();
}
Run Code Online (Sandbox Code Playgroud)

我可以用 …

.net c# task-parallel-library async-await

9
推荐指数
1
解决办法
1006
查看次数

跟踪c#/ .NET任务流程

我试图找到一种方法来跟踪异步任务执行流程的方式,以便在任务中很容易理解,启动它的原始流程是什么.我需要它主要用于记录,调试和保留特定执行流的一种堆栈跟踪.

例如:如果我的服务器具有来自多个IP的许多客户端,并且服务器需要为涉及许多异步操作的每个客户端执行工作流,则每个执行流程涉及许多不同的任务; 记录这样的流程是困难的,特别是在使用async/await机制时.

我还没有找到一种方法来包装任务,对于每个执行的任务,我会在记录时知道初始流程描述.例如,如果我为具有描述的操作启动新的任务流程 - "照顾10.0.3.4客户端",我希望能够在从该流程创建的任何任务中为此流程中的每个日志项添加此描述.

仅使用线程时,它很容易,因为您有线程静态变量.任务是不可能的......我甚至试图创建我自己的任务调度程序,它将包装任何使用它的任务(即使在使用async/await方法时)但由于任务调度程序库有时会使用新线程(尽管存在没有任何使用新线程的隐式请求) - 该方法TryExecuteTaskInline有时可以在新线程中运行.

任何想法或建议我如何实现这一目标?

.net c# multithreading asynchronous task-parallel-library

9
推荐指数
1
解决办法
1123
查看次数

HttpClient不能正确序列化XML

在调用HttpClient的扩展方法时PostAsXmlAsync,它忽略XmlRootAttribute了类.这种行为是个错误吗?

测试

[Serializable]
[XmlRoot("record")]
class Account 
{
    [XmlElement("account-id")]
    public int ID { get; set }
}


var client = new HttpClient();
await client.PostAsXmlAsync(url, new Account())
Run Code Online (Sandbox Code Playgroud)

.net c# task-parallel-library async-await dotnet-httpclient

9
推荐指数
1
解决办法
6690
查看次数

并行.不使用所有核心

我正在使用Math.Net Numerics平行内部进行繁重的数学计算Parallel.For块.

当我在本地系统中运行4核(2*2)的代码时,它使用全部4个核心.

但是,当我在具有8个内核(4*2)的开发服务器中运行相同的代码时,它只使用4个内核.

我试过设置MaxDegreeOfParallism,但无法帮助.

知道为什么没有使用所有核心.

以下是示例代码.

Parallel.For(0,10000,(i)=>
{

 // heavy math computations using matrices
});
Run Code Online (Sandbox Code Playgroud)

c# task-parallel-library mathnet-numerics parallel.for math.net

9
推荐指数
1
解决办法
2729
查看次数