有没有什么理由让.NET随着时间的推移减少并行线程的数量?
我在许多通行证中运行计算需要数天才能完成(每次通过需要约1小时).任务是内存中数据的纯计算(从磁盘读取).我正在使用Parallel.For和Parallel.ForEach几个地方,主要任务和任务内部.许多过程中都会重复所有事情.每次传递都会正确处理类实例(内存分析器不会显示任何问题),并创建新实例.它在每次传递中重复100%相同的任务,但数学中的某些数字被更改(每次迭代的数量相同,相同的数据集).
计算机有六个核心,应用程序首先使用它们.一段时间后,它使用5,然后是4,然后是3,然后是2.查看并行堆栈(Debug-> Window-> Parallel stacks),它确认只有那么多正在运行.
为什么.NET没有在每次传递中最大化线程数?它是否根据CPU使用情况调节线程?
关于如何调试的提示?我可以强制使用多少个线程吗?
我在一堆LINQ查询上有一些GUI.查询需要一些时间来执行,所以我希望GUI能够响应并显示busyindicators和进度条.许多查询都是检查数据中存在的某些条件.如果查询返回空结果,则应用程序将继续下一个查询.如果它返回结果,则返回集将具有严重性"警告"或"错误".如果是警告,则继续执行.如果是错误,它应该停止.
许多代码使用线程池和GUI播放"乒乓".准码:
TaskFactory.StartNew(()=>
{
Run in background
}.ContinueInGui(()=>
{
Update something
}).ContinueInBackground(()=>
{
Do more work;
}).ContinueInGui(()=> etc etc
Run Code Online (Sandbox Code Playgroud)
这很整洁.但是,如果在数据中发现错误,我不会看到如何插入条件来执行不同的延续路径或中断连续链.
ContinueWithIf没有方法(谓词,委托{},TaskScheduler)我是否使用TaskCancellation,是否抛出异常?或者是否有一些我没想到的简单分支机制?
我有一个带有"开始"和"停止"按钮的应用程序,以及在按下"开始"后在后台运行的线程.我使用MVC和TPL.
我如何处理TPL中的异常,因为我从不调用Wait()方法?在任何异常我需要显示错误消息框,这个框应该在它被立即抛出后显示.
我总是在后台单线程,所以你不能在没有先前停止线程的情况下按下Start.
我正在寻找一些好的模式或最佳实践.我有一个想法,将try..catch放在线程内部,并在每个catch上调用一个事件,但我不确定这样的方法是否是好的架构决策
我们假设我有一个简单的 ActionBlock<int>
var actionBlock = new ActionBlock<int>(_ => Console.WriteLine(_));
Run Code Online (Sandbox Code Playgroud)
我可以指定一个有限的容量来启用缓冲:
var actionBlock = new ActionBlock<int>(
_ => Console.WriteLine(_),
new ExecutionDataflowBlockOptions
{
BoundedCapacity = 1000
});
Run Code Online (Sandbox Code Playgroud)
创建一个BufferBlock<T>并将其链接到actionBlock更好,它是相同的,还是多余的?
我是F#的新手,从C#开发人员的角度来理解F#中的异步.假设在C#中使用以下代码段:
var httpClient = new HttpClient();
var response = await httpClient.GetAsync(url);
response.EnsureSuccessStatusCode();
string content = await response.Content.ReadAsStringAsync();
Run Code Online (Sandbox Code Playgroud)
如何在F#中写相同的内容?
f# task-parallel-library c#-to-f# async-await dotnet-httpclient
根据我是使用基于异步/等待的代码还是基于TPL的代码,我在逻辑清理方面有两种不同的行为CallContext.
CallContext如果我使用以下async/await代码,我可以完全按照我的预期设置和清除逻辑:
class Program
{
static async Task DoSomething()
{
CallContext.LogicalSetData("hello", "world");
await Task.Run(() =>
Debug.WriteLine(new
{
Place = "Task.Run",
Id = Thread.CurrentThread.ManagedThreadId,
Msg = CallContext.LogicalGetData("hello")
}))
.ContinueWith((t) =>
CallContext.FreeNamedDataSlot("hello")
);
return;
}
static void Main(string[] args)
{
DoSomething().Wait();
Debug.WriteLine(new
{
Place = "Main",
Id = Thread.CurrentThread.ManagedThreadId,
Msg = CallContext.LogicalGetData("hello")
});
}
}
Run Code Online (Sandbox Code Playgroud)
以上输出如下:
{Place = Task.Run,Id = 9,Msg = world}
{Place = Main,Id = 8,Msg =}
注意,Msg =这表明CallContext主线程已被释放且为空.
但是,当我切换到纯TPL/TAP代码时,我无法达到同样的效果......
class Program
{ …Run Code Online (Sandbox Code Playgroud) 我有一个场景,我必须保持引用计数对象的给定键ConcurrentDictionary,如果引用计数达到0,我想删除键.这必须是线程安全的,因此我打算使用ConcurrentDictionary.
示例程序如下.在并发字典中,我有键和值,值是KeyValuePair,它保存我的自定义对象和引用计数.
ConcurrentDictionary<string, KeyValuePair<object, int>> ccd =
new ConcurrentDictionary<string, KeyValuePair<object, int>>();
// following code adds the key, if not exists with reference
// count for my custom object to 1
// if the key already exists it increments the reference count
var addOrUpdateValue = ccd.AddOrUpdate("mykey",
new KeyValuePair<object, int>(new object(), 1),
(k, pair) => new KeyValuePair<object, int>(pair.Key, pair.Value + 1));
Run Code Online (Sandbox Code Playgroud)
现在我想要一种方法来在引用计数达到0时删除密钥.我在想,删除带有ConcurrentDictionary键和谓词的方法,如果谓词返回'true'则删除密钥.例.
ConcurrentDictionary.remove(TKey, Predicate<TValue> ).
Run Code Online (Sandbox Code Playgroud)
没有这样的方法ConcurrentDictionary,问题是如何以线程安全的方式做同样的事情?
.net c# multithreading task-parallel-library concurrentdictionary
以下是一个完整的控制台程序,它重现了我遇到的一个奇怪的错误.该程序读取包含远程文件URL的文件,每行一个.它会激活50个线程来下载它们.
static void Main(string[] args)
{
try
{
string filePath = ConfigurationManager.AppSettings["filePath"],
folder = ConfigurationManager.AppSettings["folder"];
Directory.CreateDirectory(folder);
List<string> urls = File.ReadAllLines(filePath).Take(10000).ToList();
int urlIX = -1;
Task.WaitAll(Enumerable.Range(0, 50).Select(x => Task.Factory.StartNew(() =>
{
while (true)
{
int curUrlIX = Interlocked.Increment(ref urlIX);
if (curUrlIX >= urls.Count)
break;
string url = urls[curUrlIX];
try
{
var req = (HttpWebRequest)WebRequest.Create(url);
using (var res = (HttpWebResponse)req.GetResponse())
using (var resStream = res.GetResponseStream())
using (var fileStream = File.Create(Path.Combine(folder, Guid.NewGuid() + url.Substring(url.LastIndexOf('.')))))
resStream.CopyTo(fileStream);
}
catch (Exception ex)
{
Console.WriteLine("Error downloading img: …Run Code Online (Sandbox Code Playgroud) 我正处于这样一种情况:我正在处理一系列任务(启用驱动器,更改位置,等待停止,禁用).
'wait for'监视一个IObservable<Status>,我想等待(所以我可以通过它ContinueWith和其他任务).
我开始了下列任务内的用户的OnNext处理,但那只是丑陋.我现在想出的是这种扩展方法:
public static Task<T> WaitFor<T>(this IObservable<T> source, Func<T, bool> pred)
{
var tcs = new TaskCompletionSource<T>();
source
.Where(pred)
.DistinctUntilChanged()
.Take(1) //OnCompletes the observable, subscription will self-dispose
.Subscribe(val => tcs.TrySetResult(val),
ex => tcs.TrySetException(ex),
() => tcs.TrySetCanceled());
return tcs.Task;
}
Run Code Online (Sandbox Code Playgroud)
(更新了svick的处理建议OnCompleted和OnError)
Where和DistinctUntilChanged正确的顺序?(我认为他们是)希望这不是重复,但这里有5000多个问题,"并非所有代码路径都返回值"!
很简单,为什么这个非泛型实现的方法编译得很好:
public static async Task TimeoutAfter(this Task task, int millisecondsTimeout)
{
if (task == await Task.WhenAny(task, Task.Delay(millisecondsTimeout)))
await task;
else
throw new TimeoutException();
}
Run Code Online (Sandbox Code Playgroud)
这种使方法通用的尝试产生Return state missing/ ... not all code paths return a value警告/错误?:
public static async Task<T> TimeoutAfter<T>(this Task<T> task, int millisecondsTimeout)
{
if (task == await Task.WhenAny(task, Task.Delay(millisecondsTimeout)))
await task;
else
throw new TimeoutException();
}
Run Code Online (Sandbox Code Playgroud) c# ×8
.net ×4
async-await ×3
asynchronous ×3
c#-4.0 ×1
c#-5.0 ×1
c#-to-f# ×1
f# ×1
task ×1
tpl-dataflow ×1