仿真进ReadAsyncReadAsync

2023-09-05 04:24:23 作者:几许清风

在净4.5存在上从流异步读取,同时监测取消标记Stream类的方法。

In .Net 4.5 there exists a method on the Stream class which read asynchronously from a stream while monitoring the cancellation token.

ReadAsync : 
       buffer:byte[] * 
       offset:int * 
       count:int * 
       cancellationToken:CancellationToken -> Task<int>

如果另一个线程应该先触发取消标记,然后关闭流,这样才能确保之前ReadAsync抛出一个异常读线程将被取消?

If another thread should first trigger the cancellation token then closes the stream, then is it guaranteed that the reading thread will be cancelled before ReadAsync throws an exception?

我可以使用.net 4.0框架和F#异步工作流,而不ReadAsync(没有过载,它接受一个取消标记进行监测)以某种方式实现这一目标的保证?

Can I somehow achieve this guarantee using the .Net 4.0 framework and F# asynchronous workflows without ReadAsync(which has no overload which accepts a cancellation token to be monitored)?

推荐答案

这特殊的重载基本上是无用的,除非你链接多个任务,一起和ndash的; 的CancellationToken 在进入到 ReadAsync 方法调用才能确认,而不是当底层流.BeginRead 调用执行。

This particular overload is basically useless unless you're chaining multiple tasks together – cancellationToken is only checked upon entry to the ReadAsync method call, and not while the underlying Stream.BeginRead call is executing.

code从ILSpy倾倒:

Code dumped from ILSpy:

public virtual Task<int> ReadAsync(byte[] buffer,
                                   int offset,
                                   int count,
                                   CancellationToken cancellationToken)
{
    if (!cancellationToken.IsCancellationRequested)
        return this.BeginEndReadAsync(buffer, offset, count);
    return Task.FromCancellation<int>(cancellationToken);
}

正如你所看到的,的CancellationToken 不转发到 BeginEndReadAsync 通话和 BeginEndReadAsync 的来讲仅仅是实施 Stream.BeginRead

As you can see, cancellationToken is not forwarded into the BeginEndReadAsync call, and BeginEndReadAsync is merely implemented in terms of Stream.BeginRead:

private Task<int> BeginEndReadAsync(byte[] buffer, int offset, int count)
{
    return TaskFactory<int>.FromAsyncTrim<Stream, Stream.ReadWriteParameters>(
        this,
        new Stream.ReadWriteParameters
        {
            Buffer = buffer,
            Offset = offset,
            Count = count
        },
        (Stream stream, Stream.ReadWriteParameters args, AsyncCallback callback, object state) =>
            stream.BeginRead(args.Buffer, args.Offset, args.Count, callback, state),
        (Stream stream, IAsyncResult asyncResult) =>
            stream.EndRead(asyncResult)
    );
}

目前这一点上,已经是那些由派生流类型,它从类型而有所不同,以键入只保证

At this point, the only guarantees you have are those made by the derived stream type, which vary from type to type.

注意,这是基于当前的.Net 4.5比特,并且执行当然是受在未来发生变化。功能

相关推荐
 
精彩推荐
图片推荐