我发现[...] Async和Begin [...] .net异步API之间存在差异,但这个答案让我有点困惑.
谈到这些模式,斯蒂芬说:
大多数*异步方法(具有相应的*已完成事件)正在使用基于事件的异步模式.较旧(但仍然完全有效)的Begin*和End*是一种称为异步编程模型的模式.
Socket类是此规则的一个例外; 它的*异步方法没有任何相应的事件; 它本质上只是APM以避免过多内存分配的方式完成的.
我得到它使用*Async方法更有效,至少在套接字方面.但后来他提到任务并行库:
但是,APM和EBAP都被基于任务并行库的更灵活的方法所取代.由于TPL可以轻松地包装APM,因此较旧的类可能不会直接更新; 扩展方法用于为旧的APM方法提供Task等价物.
我在MSDN上发现了TPL和传统.NET异步编程,我知道TPL的基础知识,创建任务,取消,延续等等,但我仍然无法理解这些:
异步编程模型(APM)和基于事件的异步模式(EAP)相互比较的优势是什么?TPL如何轻松地包装 APM意味着APM和EAP都被 TPL 取代?
最重要的是:我应该在套接字编程中使用哪个;
c# sockets design-patterns asynchronous task-parallel-library
我在C#,VS2012,WPF 4.5中有以下代码.我的期望是,.ContinueWith将在任务完成后执行(这是一个延续的完整目的,不是吗?).
这应该导致值为2英寸finalResult.
int myTestInt = 0;
Task task = Task.Factory.StartNew(async () =>
{
myTestInt = 1;
await Task.Delay(TimeSpan.FromSeconds(6));
myTestInt = 2;
}).ContinueWith(_ =>
{
int finalResult = myTestInt;
});
Run Code Online (Sandbox Code Playgroud)
实际上,finalResult被赋值为1.所以似乎await已经在声明中开始了延续.
这是预期的行为吗?我在这里错过了什么吗?ContinueWith任务完成后我不能依靠启动吗?
更新:
Justin的回答激发了我检查以下内容:
int myTestInt = 0;
Task task=Task.Factory.StartNew(async () =>
{
myTestInt = 1;
await Task.Delay(TimeSpan.FromSeconds(6));
myTestInt = 2;
});
task.Wait();
int result2 = myTestInt;
Run Code Online (Sandbox Code Playgroud)
finalResult仍设置为1.是否无法可靠地等待包含awaits 的任务完成?
这是启动多个任务的示例代码
Task.Factory.StartNew(() =>
{
//foreach (KeyValuePair<string, string> entry in dicList)
Parallel.ForEach(dicList,
entry =>
{
//create and add the Progress in UI thread
var ucProgress = (Progress)fpPanel.Invoke(createProgress, entry);
//execute ucProgress.Process(); in non-UI thread in parallel.
//the .Process(); must update UI by using *Invoke
ucProgress.Process();
System.Threading.Thread.SpinWait(5000000);
});
});
.ContinueWith(task =>
{
//to handle exceptions use task.Exception member
var progressBar = (ProgressBar)task.AsyncState;
if (!task.IsCancelled)
{
//hide progress bar here and reset pb.Value = 0
}
},
TaskScheduler.FromCurrentSynchronizationContext() //update UI from UI thread
); …Run Code Online (Sandbox Code Playgroud) 在使用数据流后,我遇到了一个新问题.我想限制所有块的输入队列.我的产品块(ActionBlock)正在快速创建5000个元素并将它们发布到广播块.因此,如果我将广播块的BoundedCapacity设置为100,则会抛出大量数据.但是我希望生产块等待我的缓冲区输入队列中的新槽.
有没有办法摆脱这个问题?
我有以下程序(我从http://blogs.msdn.com/b/csharpfaq/archive/2010/06/01/parallel-programming-in-net-framework-4-getting-started.aspx获得)使用Parallel.For循环拆分任务
class Program
{
static void Main(string[] args)
{
var watch = Stopwatch.StartNew();
Parallel.For(2, 20, (i) =>
{
var result = SumRootN(i);
Console.WriteLine("root {0} : {1} ", i, result);
});
Console.WriteLine(watch.ElapsedMilliseconds);
Console.ReadLine();
}
public static double SumRootN(int root)
{
double result = 0;
for (int i = 1; i < 10000000; i++)
{
result += Math.Exp(Math.Log(i) / root);
}
return result;
}
}
Run Code Online (Sandbox Code Playgroud)
当我多次运行此测试时,我会得到以下时间:
1992年,2140年,1783年,1863年等等
我的第一个问题是,为什么时代总是不同?我每次都在进行完全相同的计算,但每次时间都不同.
现在,当我添加以下代码以使用我CPU上的所有可用处理器时:
var parallelOptions = new ParallelOptions
{
MaxDegreeOfParallelism …Run Code Online (Sandbox Code Playgroud) 在WPF/c#应用程序中,使用大约50-200个短生存工作线程创建Task.Factory.StartNew它需要在新创建的线程开始执行之前1到10秒.
这个非常慢的线程执行开始的原因是什么?
更新: 延迟是500毫秒
我有一个套接字服务器,需要在接受客户端的循环上运行,所以我发现在函数编程中,使用了一个递归循环:
let awaitConnections (wsl:WebSocketListener) =
let rec loop ()=
async {
let! ws = Async.AwaitTask (wsl.AcceptWebSocketAsync(cancellation.Token) )
printfn "Connection from %s" (ws.RemoteEndpoint.Address.ToString())
Async.Start <| awaitMessages ws
do! loop()}
loop()
Run Code Online (Sandbox Code Playgroud)
通过执行以下操作调用此代码:
Async.Start <| awaitConnections listener
Run Code Online (Sandbox Code Playgroud)
考虑到应用程序连续运行,我应该使用迭代方法吗?该rec方法是否创建嵌套执行堆栈?
另外,我想在循环结束后做一些事情,比如:
let awaitConnections (wsl:WebSocketListener) =
let rec loop ()=
async {
let! ws = Async.AwaitTask (wsl.AcceptWebSocketAsync(cancellation.Token) )
printfn "Connection from %s" (ws.RemoteEndpoint.Address.ToString())
Async.Start <| awaitMessages ws
do! loop()}
loop()
printf "The loop ended" // <-- this line
Run Code Online (Sandbox Code Playgroud)
但是后来因为awaitConnections返回类型而无法编译.我怎么能这样做?我这样做了吗?
为什么以下异步递归失败StackOverflowException,为什么当计数器变为零时,它恰好发生在最后一步?
static async Task<int> TestAsync(int c)
{
if (c < 0)
return c;
Console.WriteLine(new { c, where = "before", Environment.CurrentManagedThreadId });
await Task.Yield();
Console.WriteLine(new { c, where = "after", Environment.CurrentManagedThreadId });
return await TestAsync(c-1);
}
static void Main(string[] args)
{
Task.Run(() => TestAsync(5000)).GetAwaiter().GetResult();
}
Run Code Online (Sandbox Code Playgroud)
输出:
...
{ c = 10, where = before, CurrentManagedThreadId = 4 }
{ c = 10, where = after, CurrentManagedThreadId = 4 }
{ c = 9, where = before, CurrentManagedThreadId = 4 … 以下C#代码:
class Program
{
static readonly List<TaskCompletionSource<bool>> buffer =
new List<TaskCompletionSource<bool>>();
static Timer timer;
public static void Main()
{
var outstanding = Enumerable.Range(1, 10)
.Select(Enqueue)
.ToArray();
timer = new Timer(x => Flush(), null,
TimeSpan.FromSeconds(1),
TimeSpan.FromMilliseconds(-1));
try
{
Task.WaitAll(outstanding);
}
catch {}
Console.ReadKey();
}
static Task Enqueue(int i)
{
var task = new TaskCompletionSource<bool>();
buffer.Add(task);
return task.Task;
}
static void Flush()
{
try
{
throw new ArgumentException("test");
}
catch (Exception e)
{
foreach (var each in buffer)
{
var lenBefore = …Run Code Online (Sandbox Code Playgroud) 我有一个具有以下签名的方法:
public async Task<Result> CreateAsync(T entity)
{
try
{
await _c.CreateItemAsync(entity);
return Result.Ok();
}
catch (Exception e)
{
return Handle(e); // returns a `Result`
}
}
Run Code Online (Sandbox Code Playgroud)
_c 是ContainerCosmosDB 的。
现在,我有另一种方法是这样的:
public Task<Result> CreateUserAsync(User user)
{
var userEntity = new UserEntity { Id = user.Id, Name = user.Name };
return CreateAsync(userEntity);
}
Run Code Online (Sandbox Code Playgroud)
Result.Ok()是自定义类的一个非常简单的静态方法Result:
class Result
{
public static Result Ok() { return new Result(); }.
}
Run Code Online (Sandbox Code Playgroud)
因此,我有两种方法,一种是Task<Result> CreateUserAsync(User user),它返回一个简单的Task,而不等待其中的任何内容,但我最后调用的另一个任务return CreateAsync(userEntity);等待其中的内容。 …
c# ×9
.net ×4
async-await ×3
asynchronous ×3
.net-4.0 ×1
f# ×1
f#-3.0 ×1
sockets ×1
tpl-dataflow ×1
wpf ×1