Solved

C# async & await

Posted on 2015-01-15
4
141 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 74

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 85

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

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
C# remove trailing commas from csv file 10 52
Object Oriented Best Practice 5 35
C# Update Status Bar.... 1 24
ConsoleSql 1 18
Real-time is more about the business, not the technology. In day-to-day life, to make real-time decisions like buying or investing, business needs the latest information(e.g. Gold Rate/Stock Rate). Unlike traditional days, you need not wait for a fe…
Performance in games development is paramount: every microsecond counts to be able to do everything in less than 33ms (aiming at 16ms). C# foreach statement is one of the worst performance killers, and here I explain why.
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…
This video discusses moving either the default database or any database to a new volume.

760 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

Need Help in Real-Time?

Connect with top rated Experts

20 Experts available now in Live!

Get 1:1 Help Now