Solved

C# async & await

Posted on 2015-01-15
4
165 Views
Last Modified: 2015-01-18
Hi Experts,

I want to enumerate files in a folder and then process each file.  Normally I would have done this by creating a thread and updating the UI after each file was processed with the result.

Now I want to do this in an async and await style... I'm a bit stuck with code that looks a bit like this:

        public async void ProcessActions()
        {
            while (!m_bAllActionsProcessed)
                await Task.Run(() => ProcessNextAction());
        }

        private async Task ProcessNextAction()
        {
            if (m_nCurrentAction >= m_Actions.Count)
            {
                m_bAllActionsProcessed = true;
                return; // done.
            }

            Action<object> action = (object obj) =>
            {
                DirectoryAction directoryAction = m_Actions[m_nCurrentAction];
                DirectoryInfo info = new DirectoryInfo(directoryAction.GetDirectory());
                FileInfo[] files = info.GetFiles("*", directoryAction.GetRecurse() ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly);
                foreach (FileInfo fileInfo in files)
                    HandleFile(fileInfo);
            };

            // and now -->  also, how do I run this task??

Open in new window


Thanks!
Mike
0
Comment
Question by:thready
  • 2
4 Comments
 
LVL 1

Author Comment

by:thready
ID: 40552754
Somehow I think I'm better off on this one using good old threads....
0
 
LVL 75

Accepted Solution

by:
käµfm³d   👽 earned 250 total points
ID: 40552864
First, you should check out the Channel 9 videos on async/await.

Second, as you'll find out in the videos, you should not be using async void for anything other than an event handler.

Third, async/await is good for I/O-bound operations, not CPU-bound operations. The reading of the files from disk is a good candidate for async/await; the processing of the files depends on what you mean by "processing" as to whether or not async/await makes sense.
0
 
LVL 86

Assisted Solution

by:Mike Tomlinson
Mike Tomlinson earned 250 total points
ID: 40552886
Not sure how things are getting fired off...or how your boolean and "m_nCurrentAction" variable are getting changed,  but try something like this out:
        private async void button1_Click(object sender, EventArgs e)
        {
            button1.Enabled = false;

            while (!m_bAllActionsProcessed) // <-- how is "m_bAllActionsProcessed" getting changed?...
                await Task.Run(() => ProcessNextAction());

            MessageBox.Show("Done!");
            button1.Enabled = true;
        }

        private void ProcessNextAction()
        {
            DirectoryAction directoryAction = m_Actions[m_nCurrentAction]; // <-- how is "m_nCurrentAction" getting changed?...
            DirectoryInfo info = new DirectoryInfo(directoryAction.GetDirectory());
            FileInfo[] files = info.GetFiles("*", directoryAction.GetRecurse() ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly);
            foreach (FileInfo fileInfo in files)
            {
                label1.Invoke((MethodInvoker)delegate { label1.Text = fileInfo.FullName; }); // some kind of progress update
                HandleFile(fileInfo);
            }   
        }

Open in new window

0
 
LVL 1

Author Closing Comment

by:thready
ID: 40556723
async & await are God's gift to programming.  Thanks for your help!
0

Featured Post

Free Tool: Postgres Monitoring System

A PHP and Perl based system to collect and display usage statistics from PostgreSQL databases.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Summary: Persistence is the capability of an application to store the state of objects and recover it when necessary. This article compares the two common types of serialization in aspects of data access, readability, and runtime cost. A ready-to…
Whether you've completed a degree in computer sciences or you're a self-taught programmer, writing your first lines of code in the real world is always a challenge. Here are some of the most common pitfalls for new programmers.
This is Part 3 in a 3-part series on Experts Exchange to discuss error handling in VBA code written for Excel. Part 1 of this series discussed basic error handling code using VBA. http://www.experts-exchange.com/videos/1478/Excel-Error-Handlin…
A short tutorial showing how to set up an email signature in Outlook on the Web (previously known as OWA). For free email signatures designs, visit https://www.mail-signatures.com/articles/signature-templates/?sts=6651 If you want to manage em…

733 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question