gpt4 book ai didi

c# - 多线程-不了解情况

转载 作者:太空宇宙 更新时间:2023-11-03 11:04:05 24 4
gpt4 key购买 nike

        var tokenSource2 = new CancellationTokenSource();
CancellationToken ct = tokenSource2.Token;

var task = Task.Factory.StartNew(() => {
Thread.Sleep(4000);
Console.WriteLine("Done");
ct.ThrowIfCancellationRequested();
}, ct);

Thread.Sleep(1000); Look here! <---
tokenSource2.Cancel();

try
{
Console.WriteLine("Wait");
task.Wait();
}
catch (Exception e)
{
Console.WriteLine("Task was canceled");
}

我不明白为什么如果我评论这一行一切正常并且在主线程中捕获异常,但是如果我离开这一行异常会在 ct.ThrowIfCancellationRequested() 行的子线程中抛出;在这两种情况下,我们都有一个取消 token 实例。我是多线程的新手,所以我绝对想念一些东西。

我试了下一段代码

    static void Main(string[] args)
{
Thread.CurrentThread.Name = "Main";

Console.WriteLine("Name of the current thread is " + Thread.CurrentThread.Name);

var tokenSource2 = new CancellationTokenSource();
CancellationToken ct = tokenSource2.Token;
var task = Task.Factory.StartNew(() =>
{
Thread.Sleep(4000);
Console.WriteLine("Done");

try
{
ct.ThrowIfCancellationRequested(); // If I remove the try/catch here will be unhandled exception
}
catch (OperationCanceledException exp)
{
Console.WriteLine("Task was started then canceled");
}

}, ct);//ontinueWith(OnProcessImageEnded);

Thread.Sleep(1000);
tokenSource2.Cancel();

try
{
Console.WriteLine("Wait");
task.Wait();
}
catch (Exception e)
{
Console.WriteLine("Task was canceled");
}

Console.WriteLine("Task was finished");

Console.WriteLine(task.Status);

我现在在任务线程中处理异常,但它导致任务状态未设置为已取消。我认为这是因为现在任务无法捕获异常来处理它。什么是正确的方法?

我找到了 http://msdn.microsoft.com/en-us/library/ee191553.aspx这个例子和它有同样的问题!如果我们在执行期间按下“c”,当我们尝试通过调用 externalToken.ThrowIfCancellationRequested() 重新抛出时,它将抛出未处理的异常; ……我一头雾水。我正在使用 x64 Win 7、4.5 .net 框架

最佳答案

当您评论该行时,我们的任务很可能在开始之前就被取消了。因此你得到了异常(exception)。当您添加 sleep 时 - 大多数情况下它会启动,因此在调用 ThrowIfCancellationRequested

时会在任务中取消

关于c# - 多线程-不了解情况,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16601722/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com