Async method to return true or false in a task

I know that a method asynccan only return voidor Task. I read similar exception handling methods inside methods async. And I'm new to programming async, so I'm looking for a direct solution.

My method asynclaunches an Sql request. If the request was ok, he should notify the caller using Boolean trueand otherwise a false. My method is currently invalid, so I don't know.

private async void RefreshContacts()
{
    Task refresh = Task.Run(() =>
    {
        try
        {
            // run the query
        }
        catch { }
    }
    );
    await refresh;           
}

I just would like to change asyncto Taskso that the catchmethod returns in my expression falseand otherwise a true.

+4
source share
3

, Task<bool>, :

private async Task<bool> RefreshContactsAsync()
{
    try
    {
        ...
    }
    catch // TODO: Catch more specific exceptions
    {
        return false;
    }
    ...
    return true;
}

, , , .

+11

Task<bool>. , , bool. jon skeet , , , , szenario

 private async Task<bool> RefreshContacts()
    {
        Task refresh = Task.Run(() =>
        {
            try
            {
                // run the query
                      return true;
        }
        catch { return false;}      
}

PS: , , , , - async. Task.FromResult(true) :

 private Task<bool> RefreshContacts()
 {
     ....
    return Task.FromResult(true)
 }
+2

, , . . Microsoft, .

, , bool string .

I am posting C # code here for posterity:

using System;
using System.Linq;
using System.Threading.Tasks;

public class Example
{
   public static void Main()
   {
      Console.WriteLine(ShowTodaysInfo().Result);
   }

   private static async Task<string> ShowTodaysInfo()
   {
      string ret = $"Today is {DateTime.Today:D}\n" +
                   "Today hours of leisure: " +
                   $"{await GetLeisureHours()}";
      return ret;
   }

   static async Task<int> GetLeisureHours()  
   {  
       // Task.FromResult is a placeholder for actual work that returns a string.  
       var today = await Task.FromResult<string>(DateTime.Now.DayOfWeek.ToString());  

       // The method then can process the result in some way.  
       int leisureHours;  
       if (today.First() == 'S')  
           leisureHours = 16;  
       else  
           leisureHours = 5;  

       return leisureHours;  
   }  
}
// The example displays output like the following:
//       Today is Wednesday, May 24, 2017
//       Today hours of leisure: 5
// </Snippet >
0
source

Source: https://habr.com/ru/post/1598670/


All Articles