question

PrashantSharma-9315 avatar image
0 Votes"
PrashantSharma-9315 asked JarvanZhang-MSFT commented

Wait for async Task for first method in xamarin froms

I am using async and await in my project and my first method is running in second method for ex- when data will save then print command will run print is depend on save and print command must run after save , but in my code sometime print command do not wait for save command execute ,that why I am getting deadlock error and Violation of PRIMARY KEY constraint in database. I am sharing my code. Thank u for help


     public async void ExecutePrintCommand()
        {
            UserDialogs.Instance.ShowLoading("Saving", MaskType.Clear);
            await Task.Delay(1000);

           try
            {
               
             var SaveStatus = await Save();

                            
             if SaveStatus == 1)
             {

                 UserDialogs.Instance.ShowLoading("Printing");
                 await Task.Delay(1000);
                    
                 await Print();


                 await App.Current.MainPage.Navigation.PushAsync(new RootPage());

             }
             else
             {
                 Device.BeginInvokeOnMainThread(() =>
                 {
                     navigation.PopAsync();

                 });
             }


         }
dotnet-csharpdotnet-xamarin
· 7
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

but in my code sometime print command do not wait for save command execute

Hi, PrashantSharma-9315. Do you mean the 'Print' is executed without waiting for the 'Save' completed? The code should not be called unless the value of 'SaveStatus' is correct. Please add a breakpoint to debug to check that.

1 Vote 1 ·

yes yes it is correct as u said and as i re-searched on my codes that save command is running twice because my database is giving me primary key voilation error , i have saved the error log on my db and the inserting time and error time diffrence is in mili sec ,so i guess that save code is running twice.

1 Vote 1 ·

Thanks for sharing the info.

0 Votes 0 ·

Hi, did you get what caused the code to run twice?

0 Votes 0 ·

What the database you are using?
Try to put delay before

 if SaveStatus == 1)


0 Votes 0 ·

ms sql server 2012

0 Votes 0 ·

Hi, did you get what caused the code to run twice?

0 Votes 0 ·

0 Answers