csharp System.Threading.Tasks.Taskの结果と例外のサンプル

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了csharp System.Threading.Tasks.Taskの结果と例外のサンプル相关的知识,希望对你有一定的参考价值。

void Main()
{
  Exec().Wait();
}

async Task Exec()
{
  var result1 = await DoTask1();
  result1.Dump();
  
  var result2 = await DoTask2();
  result2.Dump();
  
  try
  {
    var result3 = await DoTask3();
    result3.Dump();
  }
  catch (MyException myEx)
  {
    myEx.Dump();
  }
  
  try
  {
    await DoTask4();
  }
  catch(MyException myEx)
  {
    myEx.Dump();
  }
  
  try
  {
    DoTask3().Wait();
  }
  catch (AggregateException aggEx)
  {
    aggEx.Dump();
  }
}

Task<string> DoTask1()
{
  return Task.Run(() => 
  {
    return "hello world";
  });
}

Task<int> DoTask2()
{
  return Task.FromResult<int>(10);
}

Task<TaskResult> DoTask3()
{
  var tcs = new TaskCompletionSource<TaskResult>();
  
  Task.Run(async () =>
  {
    await Task.Delay(1000);
    tcs.SetException(new MyException("after 1000ms later"));
  });
  
  return tcs.Task;
}

async Task DoTask4()
{
  await Task.Delay(500);
  throw new MyException("task4");
}

class TaskResult
{
  public string Value { get; set; }
  
  public override string ToString()
  {
    return Value;
  }
}

class MyException : Exception
{
  public MyException(string message) : base(message) {}
}

以上是关于csharp System.Threading.Tasks.Taskの结果と例外のサンプル的主要内容,如果未能解决你的问题,请参考以下文章

csharp 例如-CSHARP-GroupDocs.Conversion.Examples.CSharp渲染,RenderPSDImageAsPath.cs

csharp 实例-CSHARP-GroupDocs.Conversion.Examples.CSharp变频-ConvertTopresentationAsPath.cs

csharp 实例-CSHARP-GroupDocs.Conversion.Examples.CSharp变频-ConvertTopresentationAsPath.cs

csharp 实例-CSHARP-GroupDocs.Conversion.Examples.CSharp变频-ConvertTopresentationAsPath.cs

csharp 例如-CSHARP-GroupDocs.Search.Examples.CSharp索引,AddDocumentToIndex.cs

csharp 例如-CSHARP-GroupDocs.Search.Examples.CSharp索引,AddDocumentToIndexAsynchronously.cs