c#在执行之前建立一个任务列表 [英] c# build a list of tasks before executing

查看:31
本文介绍了c#在执行之前建立一个任务列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在执行任务之前建立一个任务列表.这是一些示例代码:

i'm trying to build a list of tasks before executing them. here's some example code:

    public string Returnastring(string b)
    {
        return b;
    }

    public string Returnanotherstring(string a)
    {
        return a;
    }


    private void btnT_Click(object sender, EventArgs e)
    {
        bool cont = true;

        var Returnastringtask = Task.Factory.StartNew(() => Returnastring("hi"));
        var Returnanotherstringtask = Task.Factory.StartNew(() => Returnanotherstring("bye"));

        if (cont)
        {
            Task.WaitAll(new Task[] { Returnastringtask });
        }
        else
        {
            Task.WaitAll(new Task[] { Returnanotherstringtask });
        }

我知道当两个任务都运行时,这段代码的行为并不符合我的预期.我想基本上最初创建任务,然后根据布尔值执行一个或另一个.我不想在 true 或 false 条件下创建任务,因为我想避免代码复制.我的意思是,如果 cont 为真,我可能想运行任务 1、2、3、4,但如果 cont 为假,我可能想运行任务 2、3、7、8.

i know this code doesn't behave how i expect it as both tasks run. i want to basically create the tasks initially and then execute one or the other based on the bool. i don't want to create the tasks inside the true or false conditions as i want to avoid code copying. by this i mean if cont is true i might want to run tasks 1,2,3,4 but if cont is false i might want to run tasks 2,3,7,8.

推荐答案

不是使用 Task.Factory.StartNew 来创建任务(线索在名称中),而是通过将 new Task(...) 与您的 lambdas 一起使用,然后只需在您想要开始它们的条件中使用 taskName.Start().

Instead of using Task.Factory.StartNew to create the tasks (the clue is in the name), instead just create them by using new Task(...) with your lambdas, then simply use taskName.Start() inside the condition you want to begin them.

这篇关于c#在执行之前建立一个任务列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆