我有一个静态类,具有以下两种方法:
public async static void Execute()
{
var task = new Task<int>(Work);
try
{
task.Start();
await task;
Console.WriteLine("This is not reached");
}
catch (Exception e)
{
Console.WriteLine("This is not reached");
}
}
static int Work()
{
Thread.Sleep(500);
throw new Exception("Oops");
}
为什么不通过等待任务来传播异常?
答案 0 :(得分:0)
您的代码有几个“缺陷”。我会尽力为您“修复”它们,但这并不是您问题的实际答案;-)
#subreddit to use
subreddit = reddit.subreddit('test')
#summoning the bot
keyphrase = '!repostfinder'
#find comments with keyphrase
for comment in subreddit.stream.comments():
if keyphrase in comment.body:
print('Found keyphrase')
comment.reply('Keyphrase detected')
print('Replied to comment')
希望这可以为您澄清一点。
要点:
//please use Task, not void, since the framework
//might have trouble determining it's completion
public async static Task Execute()
{
// no need here to call a constructor
//var task = new Task<int>(Work);
try
{
//no need to explicitly start
//task.Start();
await Work();
Console.WriteLine("This is not reached");
}
catch (Exception e)
{
//this Will be reached :-)
Console.WriteLine("This is reached");
}
}
//we can just make this a task :-)
static async Task<int> Work()
{
//no need to await... but in this case we do..
//... since we throw an exception after the wait.
await Task.Delay(500);
throw new Exception("Jeuh!");
}
,而是使用async void
async Task
进行操作:即:尽可能多地创建自己的异步方法