Solved

C# async & await

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

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

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

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…
A theme is a collection of property settings that allow you to define the look of pages and controls, and then apply the look consistently across pages in an application. Themes can be made up of a set of elements: skins, style sheets, images, and o…
This Micro Tutorial will teach you how to censor certain areas of your screen. The example in this video will show a little boy's face being blurred. This will be demonstrated using Adobe Premiere Pro CS6.
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…

911 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

19 Experts available now in Live!

Get 1:1 Help Now