C # asynchronous file transfer - wait before loop continues

I am trying to deal with changes in .NET 4.5, mainly on asynchronous functions. To get around it, I thought I would create a small application to archive my huge collection of photos. I am best involved in this, so the application performs a dual task.

I have read many MSDN articles on using async, but I don't think I have a good enough understanding of this (because it does not work). My intention was for each photo in the source folder to be copied to the destination folder based on its date (or created if there was no metadata). At the same time, rename it to the standard naming convention and display the image, as it is archived in the image window. I wanted the application to continue to respond to requests while running, which includes an asynchronous process. Now the purpose of the application is unimportant, the thing is that my head around is asynchronous.

What actually happens, the application does not respond, archives all images as intended, but only the final image is displayed in the image window. Async starts the file transfer, and then moves on to the next image, discarding the transfer, and then moving around, etc., And so I get hundreds of open file streams, rather than waiting for them to close.

Any pointers in which I am mistaken will be appreciated. My understanding of using Tasks - shaking, returning a task serves what purpose?

imgMain is the image in the XAML file. Async / await is in the archive method, but shows all the code, as it may be relevant.

using System;
using System.Drawing.Imaging;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows;
using System.Windows.Media.Imaging;
using System.Windows.Forms;
using System.IO;

namespace PhotoArchive
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{

    private string Source 
    {
        get { return txtSource.Text; }
        set { txtSource.Text = value; }
    }

    private string Destination
    {
        get { return txtDestination.Text; }
        set { txtDestination.Text = value; }
    }


    public MainWindow()
    {
        InitializeComponent();

    }

    private void btnBrowseDataSource_Click(object sender, RoutedEventArgs e)
    {
        var dialogue = new FolderBrowserDialog();
        dialogue.ShowDialog();
        Source = dialogue.SelectedPath;

    }

    private void btnBrowseDestination_Click(object sender, RoutedEventArgs e)
    {
        var dialogue = new FolderBrowserDialog();
        dialogue.ShowDialog();
        Destination= dialogue.SelectedPath;
    }

    private void btnSort_Click(object sender, RoutedEventArgs e)
    {
        var files = Directory.GetFiles(Source, "*.*", SearchOption.AllDirectories);
        var result = from i in files
                     where i.ToLower().Contains(".jpg") || i.ToLower().Contains(".jpeg") || i.ToLower().Contains(".png")
                     select i;


        foreach (string f in result)
        {
            DateTime dest = GetDateTakenFromImage(f);
            Archive(f, Destination, dest);
        }

    }

    private async void Archive(string file, string destination, DateTime taken)
    {

        //Find Destination Path
        var sb = new StringBuilder();
        sb.Append(destination);
        sb.Append("\\");
        sb.Append(taken.ToString("yyyy"));
        sb.Append("\\");
        sb.Append(taken.ToString("MM"));
        sb.Append("\\");

        if (! Directory.Exists(sb.ToString()))
        {
            Directory.CreateDirectory(sb.ToString());
        }

        sb.Append(taken.ToString("dd_MM_yyyy_H_mm_ss_"));
        sb.Append((Directory.GetFiles(destination, "*.*", SearchOption.AllDirectories).Count()));
        string[] extension = file.Split('.');
        sb.Append("." + extension[extension.Length-1]);


        using (FileStream fs = File.Open(file, FileMode.Open))
        using (FileStream ds = File.Create(sb.ToString())) 
        {
            await fs.CopyToAsync(ds);
            fs.Close();
            File.Delete(file);
        }

        ImgMain.Source = new BitmapImage(new Uri(sb.ToString()));
    }

    //get date info
    private static Regex r = new Regex(":");

    public static DateTime GetDateTakenFromImage(string path)
    {
        using (var fs = new FileStream(path, FileMode.Open, FileAccess.Read))
        {
            using (System.Drawing.Image img = System.Drawing.Image.FromStream(fs, false, false))
            {
                PropertyItem prop;

                try
                {

                    prop = img.GetPropertyItem(36867);

                }
                catch (Exception)
                {
                    prop = img.GetPropertyItem(306);
                }

                string dateTaken = r.Replace(Encoding.UTF8.GetString(prop.Value), "-", 2);
                return DateTime.Parse(dateTaken);
            }
        }


    }
}

}

+5
source share
2 answers

- , ?

Task - async. Task , , . await Task, , ( ).

async void, . , , async , .

, Archive(), Task, , . Task , ( ) return s.

, Archive() :

private async Task Archive(string file, string destination, DateTime taken)

await ( async):

private async void btnSort_Click(object sender, RoutedEventArgs e)
{
    // snip

    foreach (string f in result)
    {
        DateTime dest = GetDateTakenFromImage(f);
        await Archive(f, Destination, dest);
    }
}

async void . async async Task ( async Task<SomeType>, ), await .

+6

Archive, , Archive . , Archive UI-.

:

  • async btnSort_Click
  • Task Archive
  • Archive btnSort_Click

TIP: , ( btnSort_Click), , "", .

0

All Articles