标签: task-parallel-library

Plinq语句在静态构造函数中陷入僵局

我遇到了这种情况,其中静态构造函数中的以下plinq语句被死锁:

static void Main(string[] args)
{
    new Blah();
}

class Blah
{
     static Blah()
     {
         Enumerable.Range(1, 10000)
            .AsParallel()
            .Select(n => n * 3)
            .ToList();
     }
}
Run Code Online (Sandbox Code Playgroud)

它仅在构造函数是静态时发生.请有人向我解释一下.

是TPL错误吗?编译器?我?

.net c# plinq task-parallel-library

8
推荐指数
1
解决办法
560
查看次数

限制同时执行的任务的数量

考虑这个庞大的任务池:

var tasks = new Task[4]
    {
        Task.Factory.StartNew(() => DoSomething()),
        Task.Factory.StartNew(() => DoSomething()),
        Task.Factory.StartNew(() => DoSomething()),
        Task.Factory.StartNew(() => DoSomething()),
        Task.Factory.StartNew(() => DoSomething())
    };

Task.WaitAll(tasks);
Run Code Online (Sandbox Code Playgroud)

如果我只想同时说3个任务怎么办?我将如何在代码中实现它?

c# task-parallel-library c#-4.0

8
推荐指数
2
解决办法
7207
查看次数

什么是SynchronizationContext.IsWaitNotificationRequired?

SynchronizationContext有一个叫做的财产IsWaitNotificationRequired.其目的,文件有这样的说法:

确定是否需要等待通知.

如果需要等待通知,则为true; 否则,错误.

天哪,这澄清了事情.

究竟什么是"等待通知",何时/为什么需要/不需要?有IsWaitNotificationRequired什么东西Control.InvokeRequired,或者这是不同的东西?

.net task-parallel-library

8
推荐指数
1
解决办法
958
查看次数

如何创建已取消的任务

我正在写一个Stream类,并在ReadAsync方法中被阻止.请看一下代码,我认为它可以更好地解释我用英语做的情况.

public override Task<int> ReadAsync(byte[] buffer, int offset, int count, System.Threading.CancellationToken cancellationToken)
{
    if (!cancellationToken.IsCancellationRequested)
    {
        return _connection.ReceiveAsync(new ArraySegment<byte>(buffer, offset, count));
    }
    return // <---------------    what here?
}
Run Code Online (Sandbox Code Playgroud)

使用ILSpy我可以看到其他Stream类返回一个被取消的任务,如下所示:

return new Task<TResult>(true, default(TResult), TaskCreationOptions.None, cancellationToken); 
Run Code Online (Sandbox Code Playgroud)

但是,Task的构造函数是内部的,我无法调用它.

谷歌根本没有帮助我.

task-parallel-library async-await c#-5.0 cancellation-token

8
推荐指数
2
解决办法
2719
查看次数

如何等待Task.ContinueWith内部任务完成

看看这段代码:

    private async Task InnerTask(bool outerTaskResult)
    {
        Console.WriteLine("2");
        await Task.Factory.StartNew(() => Thread.Sleep(10000));
        Console.WriteLine("3");
    }

    private async void Button2_Click(object sender, RoutedEventArgs e)
    {
        var task = Task.FromResult(false);
        Task<Task> aggregatedTask = task.ContinueWith(task1 => InnerTask(task1.Result));
        Console.WriteLine("1");
        await aggregatedTask;
        Console.WriteLine("4");
    }
Run Code Online (Sandbox Code Playgroud)

所需的输出是:

1
2
3
4
Run Code Online (Sandbox Code Playgroud)

但我得到:

1
2
4
3
Run Code Online (Sandbox Code Playgroud)

这可能与在不同线程上执行的InnerTask有关.

我正在使用ContinueWith,因为原始代码中的任务是以这种方式动态创建和排队的.

使用.Wait()方法(见下文)有效,但我认为这是一个坏主意,因为该方法是阻塞的.

task.ContinueWith(task1 => InnerTask(task1.Result).Wait())
Run Code Online (Sandbox Code Playgroud)

这里的正确方法是什么?

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

8
推荐指数
1
解决办法
4240
查看次数

关于从异步方法同步调用CPU绑定方法的困惑

我正熟悉.NET 4.5的异步/等待构造.我正在研究RESTful Web API解决方案.我试图找出如何处理CPU绑定操作 - 1)从当前线程同步调用它,或2)使用Task.Run()?

让我们使用此页面中的示例:

async Task<int> AccessTheWebAsync()
{ 
    // You need to add a reference to System.Net.Http to declare client.
    HttpClient client = new HttpClient();

    // GetStringAsync returns a Task<string>. That means that when you await the 
    // task you'll get a string (urlContents).
    Task<string> getStringTask = client.GetStringAsync("http://msdn.microsoft.com");

    // You can do work here that doesn't rely on the string from GetStringAsync.
    DoCPUBoundWork();

    // The await operator suspends AccessTheWebAsync. 
    //  - AccessTheWebAsync can't …
Run Code Online (Sandbox Code Playgroud)

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

8
推荐指数
1
解决办法
1632
查看次数

仅使用异步任务和任务有什么区别?

例如,这段代码之间的区别

public Task<IList<NewsSentimentIndexes>> GetNewsSentimentIndexes(DateTime @from, DateTime to = new DateTime(), string grouping = "1h")
    {
        var result = _conf.BasePath
            .AppendPathSegment("news-sentiment-indexes")
            .SetQueryParams(new
            {
                from = from.ToString("s"),
                to = to.ToString("s"),
                grouping
            });

        return result
           .GetStringAsync()
           .ContinueWith(Desereialize<IList<NewsSentimentIndexes>>);
    }
Run Code Online (Sandbox Code Playgroud)

然后

 public async Task<IList<NewsSentimentIndexes>> GetNewsSentimentIndexes(DateTime @from, DateTime to = new DateTime(), string grouping = "1h")
    {
        var result = _conf.BasePath
            .AppendPathSegment("news-sentiment-indexes")
            .SetQueryParams(new
            {
                from = from.ToString("s"),
                to = to.ToString("s"),
                grouping
            });

        var newsStr =  await result.GetStringAsync();
        return JsonConvert.DeserializeObject<NewsSentimentIndexes>(newsStr);
    }
Run Code Online (Sandbox Code Playgroud)

哪一个正确或更快?只是调用这个方法需要等待或只是一个任务?

c# parallel-processing asynchronous task task-parallel-library

8
推荐指数
2
解决办法
155
查看次数

QueuedTaskScheduler在Dispose时泄漏任务?

我试图找出我在哪里做错了什么或者这是任务并行库额外的错误.下面的示例代码说明了我的场景(尽管非常简化).一旦取消注释,QueuedTaskScheduler.Dispose()原因Task.WaitAll()因为tasks数组包含状态中的几个(好的,大多数)任务而无限期地挂起WaitingToRun.

我的印象是QueuedTaskScheduler.Dispose()应该等待所有计划任务完成或完全中止它们.

任何想法如何修复现有行为都是受欢迎的.

[TestClass]
public class TestTPLX
{
    [TestMethod]
    public void CheckDisposeWorks()
    {
        var qts = new QueuedTaskScheduler();
        var ts = qts.ActivateNewQueue(100);
        var cts = new CancellationTokenSource();

        var tasks = Enumerable.Range(0, 20).Select(_ => Task.Factory.StartNew(() =>
                    {
                        Thread.Sleep(10);
                    },
                cts.Token, TaskCreationOptions.None, ts))
            .ToArray();

        cts.Cancel();

        // test hangs when line below is uncommented
        // qts.Dispose();

        Task.WaitAll(tasks);
    }
}
Run Code Online (Sandbox Code Playgroud)

更新:我设法解决了删除问题_disposeCancellation.IsCancellationRequested检查里面QueuedTaskScheduler …

.net c# task-parallel-library

8
推荐指数
0
解决办法
290
查看次数

在C#中,我正在调用一个公共API,其API限制为每秒10次调用

在C#中,我正在调用一个公共API,其API限制为每秒10次调用.API有多种方法,不同的用户可以一次调用不同的方法,因此可能会出现"速率限制达到"异常.

我有以下类结构:

public class MyServiceManager
{
    public int Method1()
    {
    }

    public void Method2()
    {
    }

    public string Method3()
    {
    }
}
Run Code Online (Sandbox Code Playgroud)

多个用户可以一次调用不同的方法,如何维护静态调用队列或任务,以便我可以监视所有请求并在一秒钟内只接受10个请求

c# multithreading task task-parallel-library

8
推荐指数
1
解决办法
719
查看次数

在IHostedService中应如何使用取消令牌?

的ASP.NET核心2.0文档定义了IHostedService界面如下:

StartAsync(CancellationToken)-在服务器启动并触发IApplicationLifetime.ApplicationStarted之后调用。StartAsync包含启动后台任务的逻辑。

StopAsync(CancellationToken)-当主机执行正常关机时触发。StopAsync包含结束后台任务并处置所有非托管资源的逻辑。如果应用程序意外关闭(例如,应用程序的进程失败),则可能不会调用StopAsync。

如果StopAsync调用了关闭服务,那么取消令牌参数有什么作用?应该如何使用它们?

c# task-parallel-library asp.net-core

8
推荐指数
1
解决办法
2489
查看次数