English 中文(简体)
C#中取消多重任务的正确方式
原标题:what is the correct way to cancel multiple tasks in c#

我有一个县,负责4项任务。 取消纽顿和点击这一变化,应取消所有4项任务。 我是否应当对所有4项任务予以同样的取消,并且是否因CancelRequested而以同样的理由对这些任务进行投票? 在阅读createlinkedtokensource后,我感到困惑。 通常如何这样做? 感谢

更新:任务.WaitAll()等到完成所有任务。 同样,一旦共同注销的原产地被确定取消,如何知道何时取消所有任务。

最佳回答

Yeah, 你就使用单一<代码>Cancellation Token所说的话是正确的。 页: 1 各项任务的编号。 你的任务应当定期检查取消的标语。

例如:

const int NUM_TASKS = 4;

CancellationTokenSource cts = new CancellationTokenSource();
CancellationToken ct = cts.Token;

Task[] tasks = new Task[NUM_TASKS];
for (int i = 0; i < NUM_TASKS; i++)
{
    tasks[i] = Task.Factory.StartNew(() =>
    {
        while (true)
        {
            Thread.Sleep(1000);
            if (ct.IsCancellationRequested)
                break;
        }
    }, ct);
}

Task.WaitAll(tasks);

页: 1 Cancel();,以取消这些任务。

www.un.org/Depts/DGACM/index_spanish.htm 更新问题:

你们要求做些什么。 一种办法是使用<代码>ct.IsCancellationRequested,在不投掷的情况下检查注销,然后使你的任务得以完成。 然后,如果所有任务都已取消,则<代码>Task.WaitAll(tasks)将完成。

I ve updated the code to reflect that change.

问题回答

是的,如果你打算的话,你应当照此行事,并以此取消一切任务。





相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

NSArray s, Primitive types and Boxing Oh My!

I m pretty new to the Objective-C world and I have a long history with .net/C# so naturally I m inclined to use my C# wits. Now here s the question: I feel really inclined to create some type of ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

How to Use Ghostscript DLL to convert PDF to PDF/A

How to user GhostScript DLL to convert PDF to PDF/A. I know I kind of have to call the exported function of gsdll32.dll whose name is gsapi_init_with_args, but how do i pass the right arguments? BTW, ...

Linqy no matchy

Maybe it s something I m doing wrong. I m just learning Linq because I m bored. And so far so good. I made a little program and it basically just outputs all matches (foreach) into a label control. ...

热门标签