在TPL(任务 - 并行 - 库)中是否有内置支持用于批处理操作?
我最近玩了一个例程,使用查找表即音译在字符数组上进行字符替换:
for (int i = 0; i < chars.Length; i++)
{
char replaceChar;
if (lookup.TryGetValue(chars[i], out replaceChar))
{
chars[i] = replaceChar;
}
}
Run Code Online (Sandbox Code Playgroud)
我可以看到这可能是平凡的并行化,所以跳进了第一次刺,我知道会因为任务太细粒度而表现更差:
Parallel.For(0, chars.Length, i =>
{
char replaceChar;
if (lookup.TryGetValue(chars[i], out replaceChar))
{
chars[i] = replaceChar;
}
});
Run Code Online (Sandbox Code Playgroud)
然后我重新编写算法以使用批处理,这样就可以将工作分成不同细粒度的不同线程.这使得线程按预期使用,并且我得到了一些接近线性的加速.
我确信必须内置支持TPL中的批处理.什么是语法,我该如何使用它?
const int CharBatch = 100;
int charLen = chars.Length;
Parallel.For(0, ((charLen / CharBatch) + 1), i =>
{
int batchUpper = ((i + 1) * CharBatch);
for (int j = i * …Run Code Online (Sandbox Code Playgroud) 我正在编写一个使用Socket的应用程序,它将非常密集,然后我真的需要使用我们在大服务器中的每个核心.我在stackoverflow中看到了问题(如何使用ThreadPool运行套接字线程?)这里只有一个答案指向此MSDN示例.
但我认为它只指向如何使它并发而不是并行,这里有人问如何cpu密集是打开一个套接字,它看起来非常密集,有人在这里说它不帮助TPL TaskFactory.FromAsync vs任务与阻塞方法和某人在这里教会如何使用TaskFactory.FromAsync(是否存在将现有的BeginXXX/EndXXX异步方法包装成异步任务的模式?).
如何保持套接字操作并行和高性能,如果处理插槽问题,如断开连接,半连接套接字和消息边界是正常异步方式的头疼.如果将TPL和Task放在一起,如何处理它.
这一切都发生在Windows服务中.
我有一个Queue<T>(实际上是ConcurrentQueue<T>)等待处理的物品.但是,我不想一次只处理一个,我想同时处理n个项目,其中n是一个可配置的整数.
如何使用任务并行库进行此操作?
我知道TPL会代表开发人员对集合进行并发处理,但不确定这是否是我追求的功能.我是多线程和TPL的新手.
.net parallel-processing concurrency multithreading task-parallel-library
我想编写一个简单的套接字服务器,但是我希望它是可垂直扩展的,例如,不是每个连接创建一个线程,也不是长时间运行的任务,这可能会占用所有线程.
服务器接收包含查询的请求并流式传输任意大的结果.
我希望使用C#4中提供的技术和库来实现这一目标的惯用方法,重点是简单的代码,而不是原始性能.
重新打开 套接字服务器是可伸缩系统的有用部分.如果要水平缩放,则有不同的技术.如果您从未创建套接字服务器,则应该无法回答此问题.
我有一些包含Action(System.Action)的ConcurrentQueue.需要运行此队列中的每个操作(需要使用invoke调用).
当队列不为空时=>需要调用动作=>但是我想对将要运行的并行任务的数量进行一些限制.除此之外,可以随时向队列添加新动作.
怎么做 ?
(使用.net 4.0)
我写了一些东西,但我不确定这是最好的方法
SemaphoreSlim maxThread = new SemaphoreSlim(5);
while( !actionQueue.IsEmpty )
{
maxThread.Wait();
Task.Factory.StartNew( () =>
{
Action action;
if( actionExecution.TryDequeue( out action) )
{
action.Invoke();
}
},
TaskCreationOptions.LongRunning ).ContinueWith( ( task ) => maxThread.Release() );
}
}
Run Code Online (Sandbox Code Playgroud) 我有一个课程,可以产生无限期运行的各种任务.处理此对象时,我想阻止这些任务运行.
这是正确的方法:
public class MyClass : IDisposable
{
// Stuff
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
queueCancellationTokenSource.Cancel();
feedCancellationTokenSource.Cancel();
}
}
}
Run Code Online (Sandbox Code Playgroud) .net c# parallel-processing idisposable task-parallel-library
我有以下WCF合同:
[ServiceContract(Namespace = "http://abc/Services/AdminService")]
public interface IAdminService
{
[OperationContract]
string GetServiceVersion();
// More methods here
}
Run Code Online (Sandbox Code Playgroud)
这GetServiceVersion是一个返回一些字符串的简单方法.它用作ping来检查服务是否可访问.
现在我想异步调用它,认为它比使用.NET线程在后台调用它更有效.
所以,我为此提出了以下接口:
[ServiceContract(Namespace = "http://abc/Services/AdminService")]
public interface IMiniAdminService
{
[OperationContract(Action = "http://abc/Services/AdminService/IAdminService/GetServiceVersion", ReplyAction = "http://abc/Services/AdminService/IAdminService/GetServiceVersionResponse")]
Task<string> GetServiceVersionAsync();
}
Run Code Online (Sandbox Code Playgroud)
这使得可以GetServiceVersion异步调用API:
var tmp = new ChannelFactory<IAdminService>("AdminServiceClientEndpoint");
var channelFactory = new ChannelFactory<IMiniAdminService>(tmp.Endpoint.Binding, tmp.Endpoint.Address);
var miniAdminService = channelFactory.CreateChannel();
return miniAdminService.GetServiceVersionAsync().ContinueWith(t =>
{
if (t.Exception != null)
{
// The Admin Service seems to be unavailable
}
else
{
// The Admin Service is …Run Code Online (Sandbox Code Playgroud) 我最近有一种情况,我有一个ASP.NET WebAPI控制器,需要在其action方法中对另一个REST服务执行两个Web请求.我编写了我的代码,将功能完全分离为单独的方法,看起来有点像这个例子:
public class FooController : ApiController
{
public IHttpActionResult Post(string value)
{
var results = PerformWebRequests();
// Do something else here...
}
private IEnumerable<string> PerformWebRequests()
{
var result1 = PerformWebRequest("service1/api/foo");
var result = PerformWebRequest("service2/api/foo");
return new string[] { result1, result2 };
}
private string PerformWebRequest(string api)
{
using (HttpClient client = new HttpClient())
{
// Call other web API and return value here...
}
}
}
Run Code Online (Sandbox Code Playgroud)
因为我使用的HttpClient所有Web请求都必须是异步的.我之前从未使用async/await,因此我开始天真地添加关键字.首先,我将async关键字添加到PerformWebRequest(string api)方法中,然后调用者抱怨该PerformWebRequests()方法必须async也是为了使用await …
有人可以向我解释如何返回任务的结果吗?我目前正在尝试执行以下操作,但我的任务不会返回我期望的列表吗?这里有什么问题?
static void Main()
{
List<Task> tasks = new List<Task>();
List<string> sha256_hashes = new List<string>();
List<string> results = new List<string>();
sha256_hashes.Add("hash00");
sha256_hashes.Add("hash01");
sha256_hashes.Add("hash03");
foreach(string sha256 in sha256_hashes)
{
string _sha256 = sha256;
var task = Task.Factory.StartNew(() => GetAdditionalInfo(_sha256));
tasks.Add(task);
}
Task.WaitAll(tasks.ToArray());
//I want to put all the results of each task from tasks but the problem is
//I can't use the Result method from the _task because Result method is not available
//below is my plan to get all the …Run Code Online (Sandbox Code Playgroud) 请考虑以下代码:
// MyKickAssTaskScheduler is a TaskScheduler, IDisposable
using (var scheduler = new MyKickAssTaskScheduler())
{
Task foo = new Task(() => DoSomething());
foo.ContinueWith((_) => DoSomethingElse());
foo.Start(scheduler);
foo.Wait();
}
Run Code Online (Sandbox Code Playgroud)
是否ContinueWith()保证在我的调度程序上运行任务?如果没有,它将使用哪个调度程序?
c# ×9
.net ×3
asynchronous ×2
sockets ×2
async-await ×1
c#-4.0 ×1
concurrency ×1
idisposable ×1
task ×1
tcplistener ×1
wcf ×1