C# 如何对文件进行分块和流式处理
我需要用一个文件来模拟一个流。。。C# 如何对文件进行分块和流式处理,c#,C#,我需要用一个文件来模拟一个流。。。 这是我到目前为止能够制作的。。。代码可以工作,但流式传输不会发生。 我没有使用流的经验,所以希望能找到很多bug Stream chunkedStream = new MemoryStream(); var task = session.AnalyzeAsync(chunkedStream); FillStream(chunkedStream); while
这是我到目前为止能够制作的。。。代码可以工作,但流式传输不会发生。 我没有使用流的经验,所以希望能找到很多bug
Stream chunkedStream = new MemoryStream();
var task = session.AnalyzeAsync(chunkedStream);
FillStream(chunkedStream);
while (!task.Wait(500))
{
Console.Write("\r" + ((float)chunkedStream.Position / 16000) + " Seconds");
if (!chunkedStream.CanWrite)
{
break;
}
}
private static async Task FillStream(Stream chunkedStream)
{
var stream = Properties.Resources.ResourceManager.GetStream("Sample");
byte[] chunk = new byte[16000];
while (true)
{
Thread.Sleep(1000);
int index = 0;
// There are various different ways of structuring this bit of code.
// Fundamentally we're trying to keep reading in to our chunk until
// either we reach the end of the stream, or we've read everything we need.
while (index < chunk.Length)
{
int bytesRead = stream.Read(chunk, index, chunk.Length - index);
if (bytesRead == 0)
{
break;
}
index += bytesRead;
}
if (index != 0) // Our previous chunk may have been the last one
{
// SendChunk(chunk, index); // index is the number of bytes in the chunk
chunkedStream.Write(chunk, 0, chunk.Length);
}
if (index != chunk.Length) // We didn't read a full chunk: we're done
{
chunkedStream.Close();
return;
}
}
}
public async Task AnalyzeAsync(Stream voiceStream)
{
IntervalHandler();
_StreamTask = UpStreamVoiceData(voiceStream);
await _StreamTask;
}
private async Task<Result<AnalysisResult>> UpStreamVoiceData(Stream voiceStream)
{
HttpWebRequest webRequest = WebRequestExtensions.CreateJsonPostRequest(_actions.upStream);
webRequest.ReadWriteTimeout = 1000000;
webRequest.Timeout = 10000000;
webRequest.SendChunked = true;
webRequest.AllowWriteStreamBuffering = false;
webRequest.AllowReadStreamBuffering = false;
using (var requeststream = webRequest.GetRequestStream())
{
await voiceStream.CopyStreamWithAutoFlush(requeststream);
requeststream.Close();
}
return webRequest.ReadJsonResponseAs<Result<AnalysisResult>>();
}
Stream chunkedStream=newmemoryStream();
var task=session.AnalyzeAsync(chunkedStream);
FillStream(chunkedStream);
而(!task.Wait(500))
{
Console.Write(“\r”+((float)chunkedStream.Position/16000)+“秒”);
如果(!chunkedStream.CanWrite)
{
打破
}
}
私有静态异步任务FillStream(Stream chunkedStream)
{
var stream=Properties.Resources.ResourceManager.GetStream(“示例”);
byte[]chunk=新字节[16000];
while(true)
{
睡眠(1000);
int指数=0;
//有各种不同的方法来构造这段代码。
//从根本上说,我们一直在努力阅读,直到
//要么我们到达了终点,要么我们已经阅读了所有我们需要的东西。
while(索引
“代码工作,但流式传输不会发生”-什么?所以它可以工作,但不起作用?@多项式AnalyzeAAsync立即返回,而不等待数据到达。您没有显示AnalyzeAync
函数,也没有显示会话
变量的类型。@Polyman谢谢,添加了信息。