I am trying to understand the async and await.Now i want to apply async and await keyword in my current project.My process structure are:

//DataAccess 
Private List<Users> GetAllUsers()
{
   .... ;
   return List<Users>
}

//UI
List<Users> UserList=new List<Users>();
private async void Ok_ClickAsync(object sender, RoutedEventArgs e)
{
    //I want to select all user ant assign to UserList but currently it not use.
    UserList=await BindUser();    
}

private async Task<List<Users>> BindUser()
{
  List<Users> model=await Task.Run(()=>GetAllUsers());
  return model;
}
private void btnSave_Click(object sender, RoutedEventArgs e)
{
   //I want to use UserList here and want to validate process   
}

Problem is if i click save click button quickly,UserList count are 0(Actually UserList record are over 100,000).So I want to check BindUser() process is finish or not before doing validation process in Save_Click(). Please let me known for best solution and help me to understand async and await keyword. Thanks.

  • 1
    The very best resource that I know of to fully understand async in C# is this Microsoft article. In the meantime, a better place to ask your code troubleshooting question is Stack Overflow (we don't do code troubleshooting here, sorry). – Robert Harvey Jan 25 at 3:06
  • @RobertHarvey Thank you for you link and i will noted you suggestion. – Loran Jan 25 at 3:16

Use a ViewModel and a RelayCommand

Set the datacontext of your Window/UserControl to the viewmodel and bind the Button to the ICommand on your view model in xaml.

https://stackoverflow.com/questions/25099312/is-asynchronous-version-of-relaycommand-required-in-order-to-run-async-methods-c

If you are using an MVVM framework they often provide a DelegateCommand class which will let you easily create ICommands.

The CanExecute function will disable the button when the command cant execute.

  • Does this have anything to do with async? – Robert Harvey Jan 25 at 18:54
  • yes. follow this advice and you will have an async method fired when you click your button and the button will disable while it is running – Ewan Jan 26 at 8:45
  • I guess I had to click your link to get the full story. That's not exactly the best form for Stack Exchange answers. – Robert Harvey Jan 26 at 15:46
  • yes, but its an internal link. plus I figure the OPs problem is not so much the details of async, but that they are fighting the system with async event handlers in the code behind – Ewan Jan 26 at 16:34

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.