Quantcast
Viewing latest article 13
Browse Latest Browse All 19

async / await / task

Hi Karen, 

Thanks.

Reference missing.

Microsoft.office.core

Microsoft.office.interop.excel

I haven't SQL server.

Is there a way to run your sample easy?

Greetings Markus

Here I placed everything you need into a single form, it needs one button named WaitAllButton, one TextBox named textBox1. The text file can be downloaded in the link shown in the code.

Does not need any of the references you listed. If the code below does not work perhaps you are in a lower version of the .NET Framework.

using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApp1
{
    public partial class Form1 : Form
    {
        private CancellationTokenSource _cancellationTokenSource =
            new CancellationTokenSource();
        public Form1()
        {
            InitializeComponent();
        }

        private async void WaitAllButton_Click(object sender, EventArgs e)
        {
            // https://github.com/karenpayneoregon/AsynchronousSharp/blob/master/CodeSnippets/Names1.txt
            var fileName1 = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Names1.txt");

            if (!File.Exists(fileName1))
            {
                MessageBox.Show("Failed to find file, please ensure the file exists.");
                return;
            }

            var personArgs1 = new PersonArguments()
            {
                FileName = fileName1,
                FirstName = "Rebecca",
                LastName = "Clark"
            };

            var progress = new Progress<string>(value => textBox1.AppendText($"{value}{Environment.NewLine}"));
            var operations = new ShortSamples();
            await Task.Run(() => operations.Example1Async(personArgs1, progress));
        }
    }
    public class Person
    {
        public int Id { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Gender { get; set; }
        public DateTime Birthday { get; set; }
    }
    public class PersonArguments
    {
        /// <summary>
        /// File to read
        /// </summary>
        public string FileName { get; set; }
        /// <summary>
        /// First name to find
        /// </summary>
        public string FirstName { get; set; }
        /// <summary>
        /// Last name to find
        /// </summary>
        public string LastName { get; set; }
    }
    /// <summary>
    /// Custom event for reporting progress in async operations
    /// </summary>
    public class ProcessIndexingArgs : EventArgs
    {
        protected int Index;

        public ProcessIndexingArgs(int sender)
        {
            Index = sender;
        }
        public int Value => Index;

        public override string ToString()
        {
            return Index.ToString();
        }
    }
    public class ShortSamples
    {
        CancellationTokenSource _cancellationTokenSource = new CancellationTokenSource();
        CancellationToken _cancellationToken = new CancellationToken();

        public async Task Example1Async(PersonArguments personArguments, IProgress<string> progress)
        {
            Task<Person> taskOne = await Task.Factory.StartNew(async () =>
            {
                var person = new Person() { Id = -1 };

                var lines = File.ReadAllLines(personArguments.FileName);
                for (var index = 0; index < lines.Length - 1; index++)
                {
                    var lineParts = lines[index].Split(',');
                    if (lineParts[1] == personArguments.FirstName && lineParts[2] == personArguments.LastName)
                    {
                        person.Id = Convert.ToInt32(lineParts[0]);
                        person.Birthday = DateTime.Parse(lineParts[4]);
                        if (lineParts[3] == "1" || lineParts[3] == "2")
                        {
                            person.Gender = lineParts[3] == "1" ? "Female" : "Male";
                        }
                        progress.Report($"Id is {lineParts[0]}");
                        break;
                    }

                    await Task.Delay(1, _cancellationToken);
                }

                progress.Report("Task 1 complete");
                return person;

            }, _cancellationToken);

            var taskTwo = await Task.Factory.StartNew(async () =>
            {
                for (var index = 0; index < 5; index++)
                {
                    _cancellationToken.ThrowIfCancellationRequested();
                    progress.Report(index.ToString());

                    await Task.Delay(12, _cancellationToken);

                    _cancellationToken.WaitHandle.WaitOne(500);
                }

                progress.Report("Task 2 complete");
                return true;

            }, _cancellationToken);

            Task.WaitAll(taskOne, taskTwo);
            progress.Report("Both task done!");


            var personResult = taskOne.Result;

            progress.Report(personResult.Id > -1 ?
                $"Birthday: {personResult.Birthday:d} - gender: {personResult.Gender}" :
                $"Not found");
        }
    }
}


Please remember to mark the replies as answers if they help and unmarked them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.

NuGet BaseConnectionLibrary for database connections.

StackOverFlow
Image may be NSFW.
Clik here to view.
profile for Karen Payne on Stack Exchange


Viewing latest article 13
Browse Latest Browse All 19

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>