Search code examples
c#.netwcffilestream

Stream or buffer big files in WCF


I want to transfer big files via WCF tcp protocol, but I don't know which technique I should use: buffering or streaming.

I want to transfer files asynchronously and show the progress in a progress-bar control.

Streaming looks better, because I have no idea how to organize buffer in 4 Kb and read/write async with recursion method. Should i convert this method return type to Task<Stream> and call it?

private void test()
{
    Stream _stream = new FileStream("D:\\123.avi", FileMode.Open);
    using (FileStream fileStream = new FileStream("D:\\123\\123.avi", FileMode.Create))
    {
        _stream.CopyTo(fileStream);
    }
}

UPDATE Ok, I've done something like that:

    public Task<Stream> GetFileStream(string path)
        {

            Stream _stream = new FileStream(path, FileMode.Open);


            var taskSource = new TaskCompletionSource<Stream>();
            taskSource.SetResult(_stream);
            return taskSource.Task;
        }
        void GetFile()
        {
            FileStream fileStream = new FileStream("D:\\123\\123.avi", FileMode.Create);

            GetFileStream(@"D:\myFile.mkv").Result
                .CopyTo(fileStream);
        }
private void BtnButton_Click(object sender, RoutedEventArgs e)
        {
            Task task = new Task( () => { GetFile(); } );
            task.Start();

        }

What should I do to bind this process to ProgressBar?


Solution

  • If you are transferring really big files then streaming is definitely the way to go. Buffering will become a bottleneck very quickly. However, you should always measure twice and cut once whenever you deal with performance and scalability.

    Here is a nice MSDN article covering the topic of Buffering vs Streaming in WCF:

    https://msdn.microsoft.com/en-us/library/ms733742(v=vs.110).aspx

    Regarding displaying a progress bar, it should be pretty easy to calculate progress when reading the chunks of the response stream from the WCF service.

    However, your question is still too broad to be answered with more detail and concrete code.