Click here to Skip to main content
15,908,172 members
Home / Discussions / C#
   

C#

 
QuestionAppending data to existing excel file using C# Pin
Member 1296649424-Jan-17 15:34
Member 1296649424-Jan-17 15:34 
AnswerRe: Appending data to existing excel file using C# Pin
Ralf Meier24-Jan-17 22:18
mveRalf Meier24-Jan-17 22:18 
AnswerRe: Appending data to existing excel file using C# Pin
Richard MacCutchan24-Jan-17 22:34
mveRichard MacCutchan24-Jan-17 22:34 
AnswerRe: Appending data to existing excel file using C# Pin
Patrice T25-Jan-17 10:55
mvePatrice T25-Jan-17 10:55 
QuestionAwait - Async not so simple to use? Pin
Richard Andrew x6424-Jan-17 12:24
professionalRichard Andrew x6424-Jan-17 12:24 
AnswerRe: Await - Async not so simple to use? Pin
Nathan Minier24-Jan-17 14:22
professionalNathan Minier24-Jan-17 14:22 
GeneralRe: Await - Async not so simple to use? Pin
Richard Andrew x6425-Jan-17 1:41
professionalRichard Andrew x6425-Jan-17 1:41 
AnswerRe: Await - Async not so simple to use? Pin
Jon McKee24-Jan-17 17:53
professionalJon McKee24-Jan-17 17:53 
The async keyword doesn't make a function asynchronous. It gives you access to the await keyword. Await can be used on any call that returns a Task<T> or Task. Await checks whether the Task.IsCompleted is true then if not it captures the current context and sets the remaining code in the function as a continuation after the awaited task completes. Then the function returns control to its caller.

Since PerformLengthyTask is a function call executed in the UI context, when you sleep on the current thread it is sleeping the UI thread. async/await are used to easily allow asynchronous behavior when calling code which waits on something to complete execution. That something could be on a thread pool thread, an external server, another thread, or whatever. Also a method doesn't have to be async to return Task or Task<T> but an async method has to return either one of those or void.

This example will add the items to the listbox, return control back to the UI, and when the delay expires so the result gets set PerformLengthyTask will continue with return true which will set its result so button1_Click can continue with whatever it wants to do with the boolean.
C#
private async void button1_Click(object sender, EventArgs e)
        {
            Task<bool> lengthyTask = PerformLengthyTask();
            listBox.Items.AddRange(new object[] {"Hello", "There", "Code", "Project."});
            bool result = await lengthyTask;
            //Do something with result
        }

        private async Task<bool> PerformLengthyTask()
        {
            await Task.Delay(5000);
            return true;
        }
        //or not using Task.Delay
        private async Task<bool> PerformLengthyTask()
        {
            await DelayAsync(5000);
            return true;
        }
        private Task DelayAsync(int delay)
        {
            TaskCompletionSource<bool> tcs = new TaskCompletionSource<bool>();
            ThreadPool.QueueUserWorkItem(_ => 
            {
                Thread.Sleep(delay);
                tcs.SetResult(false);
            });
            return tcs.Task;
        }

TaskCompletionSource<T> has no non-generic so a dummy TResult of bool is used in DelayAsync. Note that if you don't need to synchronize back to the captured context you can use await DelayAsync(5000).ConfigureAwait(false). This is useful if you don't need to update any UI objects for example.

Your listbox might not be updating because your listbox view isn't refreshed Thumbs Up | :thumbsup:

Bonus Edit: This doesn't use async/await but accomplishes the same thing.

C#
private void button1_Click(object sender, EventArgs e)
        {
            PerformLengthyTask().ContinueWith(task =>
            {
                bool result = task.Result;
                //Do something with result
            }, TaskScheduler.FromCurrentSynchronizationContext());
            listBox.Items.AddRange(new object[] {"Hello", "There", "Code", "Project."});
        }

        private Task<bool> PerformLengthyTask()
        {
            DelayAsync(5000).ContinueWith(_ => true);
        }

        private Task DelayAsync(int delay)
        {
            TaskCompletionSource<bool> tcs = new TaskCompletionSource<bool>();
            ThreadPool.QueueUserWorkItem(_ => 
            {
                Thread.Sleep(delay);
                tcs.SetResult(false);
            });
            return tcs.Task;
        }


modified 25-Jan-17 1:39am.

GeneralRe: Await - Async not so simple to use? Pin
Richard Andrew x6425-Jan-17 1:42
professionalRichard Andrew x6425-Jan-17 1:42 
SuggestionRe: Await - Async not so simple to use? Pin
Richard Deeming25-Jan-17 3:09
mveRichard Deeming25-Jan-17 3:09 
GeneralRe: Await - Async not so simple to use? Pin
Jon McKee25-Jan-17 9:34
professionalJon McKee25-Jan-17 9:34 
GeneralRe: Await - Async not so simple to use? Pin
Richard Deeming25-Jan-17 10:23
mveRichard Deeming25-Jan-17 10:23 
GeneralRe: Await - Async not so simple to use? Pin
Jon McKee25-Jan-17 10:49
professionalJon McKee25-Jan-17 10:49 
AnswerRe: Await - Async not so simple to use? Pin
Graeme_Grant25-Jan-17 1:31
mvaGraeme_Grant25-Jan-17 1:31 
AnswerRe: Await - Async not so simple to use? Pin
Richard Deeming25-Jan-17 3:12
mveRichard Deeming25-Jan-17 3:12 
GeneralRe: Await - Async not so simple to use? Pin
Richard Andrew x6425-Jan-17 10:08
professionalRichard Andrew x6425-Jan-17 10:08 
QuestionDelegates Pin
Member 1202181724-Jan-17 2:13
Member 1202181724-Jan-17 2:13 
AnswerRe: Delegates Pin
Richard Deeming24-Jan-17 2:20
mveRichard Deeming24-Jan-17 2:20 
AnswerRe: Delegates Pin
OriginalGriff24-Jan-17 2:26
mveOriginalGriff24-Jan-17 2:26 
QuestionPlz Send Me The Simpler Answer to connect with SSIS And SSRS Both In any Version fo the Excell Pin
Member 889223723-Jan-17 23:45
Member 889223723-Jan-17 23:45 
GeneralRe: Plz Send Me The Simpler Answer to connect with SSIS And SSRS Both In any Version fo the Excell Pin
Richard MacCutchan24-Jan-17 0:42
mveRichard MacCutchan24-Jan-17 0:42 
Questionnumber converter Pin
ab_ayo23-Jan-17 1:51
ab_ayo23-Jan-17 1:51 
AnswerRe: number converter Pin
Richard MacCutchan23-Jan-17 2:07
mveRichard MacCutchan23-Jan-17 2:07 
AnswerRe: number converter Pin
Patrice T23-Jan-17 9:52
mvePatrice T23-Jan-17 9:52 
GeneralRe: number converter Pin
Ed E24-Jan-17 9:22
professionalEd E24-Jan-17 9:22 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.