Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/285.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 在任务中返回true或false的异步方法_C#_Asynchronous_Async Await - Fatal编程技术网

C# 在任务中返回true或false的异步方法

C# 在任务中返回true或false的异步方法,c#,asynchronous,async-await,C#,Asynchronous,Async Await,我知道async方法只能返回void或Task。我在async方法中读过类似的异常处理方法。我对async编程是新手,所以我正在寻找一个简单的解决方案 我的async方法运行Sql查询。如果查询正常,则应使用布尔值true通知调用者,否则将使用false通知调用者。我的方法目前是一个空白,所以我没有办法知道 private async void RefreshContacts() { Task refresh = Task.Run(() => { try

我知道
async
方法只能返回
void
Task
。我在
async
方法中读过类似的异常处理方法。我对
async
编程是新手,所以我正在寻找一个简单的解决方案

我的
async
方法运行Sql查询。如果查询正常,则应使用布尔值
true
通知调用者,否则将使用
false
通知调用者。我的方法目前是一个空白,所以我没有办法知道

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

我只想将
async
更改为
Task
,这样在
catch
语句中,方法将返回
false
,否则返回
true

将方法签名更改为
Task
。然后,如果您的方法被声明为async,您可以简单地返回一个bool值。但正如jon skeet所说,还有其他可能更好的方法来处理你的szenario

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

听起来您只需要返回一个
任务
,然后:

private async Task<bool> RefreshContactsAsync()
{
    try
    {
        ...
    }
    catch // TODO: Catch more specific exceptions
    {
        return false;
    }
    ...
    return true;
}
专用异步任务RefreshContactsAsync()
{
尝试
{
...
}
catch//TODO:捕获更具体的异常
{
返回false;
}
...
返回true;
}

就我个人而言,我不会捕捉异常,而是让调用方检查任务的错误状态,但那是另一回事。

对不起,但我认为你们都在误导这里的人。 请参阅Microsoft文章

非常简单的示例显示了如何从任务返回
bool
int
string
类型的(标量)值

我在这里发布C#代码,供子孙后代使用:

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's 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's hours of leisure: 5
// </Snippet >
使用系统;
使用System.Linq;
使用System.Threading.Tasks;
公开课范例
{
公共静态void Main()
{
Console.WriteLine(ShowTodaysInfo().Result);
}
私有静态异步任务ShowTodaysInfo()
{
string ret=$“今天是{DateTime.Today:D}\n”+
“今天的休闲时间:”+
$“{await GetLeisureHours()}”;
返回ret;
}
静态异步任务GetLeisureHours()
{  
//Task.FromResult是返回字符串的实际工作的占位符。
var today=wait Task.FromResult(DateTime.Now.DayOfWeek.ToString());
//然后,该方法可以以某种方式处理结果。
国际休闲时间;
如果(今天。第一个()=='S')
休闲时间=16小时;
其他的
休闲时间=5小时;
返回休闲时间;
}  
}
//该示例显示如下输出:
//今天是2017年5月24日星期三
//今天的休闲时间:5小时
// 

< /代码>当我将catch更改为<代码> catch {false false;} >在将返回类型更改为<代码>任务< /代码>之后,我得到了这个警告消息:“因为这个调用没有等待,所以当前方法的执行在调用完成之前继续。请考虑将‘Acess’运算符应用到调用的结果。”检查任务的错误状态听起来更有趣,你能举一个简单的例子吗?@Pedram:那么你从哪里得到这个警告,你有没有尝试过遵循它的建议?有关检查任务是否处于故障状态的信息,请参阅
任务
的文档。虽然如果您等待该任务,异常将被重试。如果我在每次调用之前添加Wait,则在调用方法
RefreshContacts()
的任何地方都会出现警告,这是否意味着我应该将运行此函数的所有函数更改为async?@Pedram:是。听起来您基本上需要后退一步,思考异步刷新联系人意味着什么……当我将catch更改为
catch{return false;}
时,在将返回类型更改为
Task
后,我收到以下警告消息:由于此调用未被等待,因此当前方法的执行将在调用完成之前继续。考虑将“Acess”操作符应用到调用的结果中。“这个消息与catch语句无关。最有可能的是,在<代码>尝试< /COD>部分中没有任何异步调用。在这种情况下,使用<代码> AsYNC/<代码>或任务是没有意义的。
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's 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's hours of leisure: 5
// </Snippet >