单击按钮时的方法的线程化

发布于 2024-12-11 02:09:43 字数 715 浏览 0 评论 0原文

我在单击按钮时调用了一些方法。

functionA()

functionB()

functionC()

这三个函数都是相互独立的,并且执行时间较长。我检查并发现通过线程我可以同时运行这三个,这将节省执行时间。

由于我是线程概念的新手,任何人都可以指导我在场景中执行线程的最简单方法或在这种情况下有用的其他方式。

编辑

同一函数中还有一个问题:

我在三个函数执行后绑定了 5 个 gridview。像这样

            gv1.DataSource = GetData("Mill");
            gv1.DataBind();

            gv2.DataSource = GetData("Factory");
            gv2.DataBind();

            gv3.DataSource = GetData("Garage");
            gv3.DataBind();

            gv4.DataSource = GetData("Master");
            gv4.DataBind();

他们都使用相同的方法来获取结果,并且他们也需要时间来加载。有什么办法可以让它们并行运行吗?我担心,因为他们使用相同的方法来获取数据。是否可以为它们做线程。如何 ?

I am calling few methods on a button click.

functionA()

functionB()

functionC()

All three functions are independent from each other and they take long time to execute. I checked and found that by threading I can run all three together which will save the execution time.

As I am new to threading concept, could anyone please guide me the simplest way I can do threading in scenario or other way which will be useful in this scenario.

EDIT

One more problem in the same function:

I am binding 5 gridviews after the three functions execution. Like this

            gv1.DataSource = GetData("Mill");
            gv1.DataBind();

            gv2.DataSource = GetData("Factory");
            gv2.DataBind();

            gv3.DataSource = GetData("Garage");
            gv3.DataBind();

            gv4.DataSource = GetData("Master");
            gv4.DataBind();

They all are using the same method for getting the result and they are also taking time to load. Is there any way I can run them parallel too? I afraid, because they are using same method to get the data. Is it possible to do threading for them. How ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

怎言笑 2024-12-18 02:09:43

我不确定 Parallel.Invoke() 如何决定并行执行什么,但如果您想确保它们并行执行,请使用线程:

var t1 = new Thread(MySlowFunction);
t1.IsBackground = true;
t1.Start();

var t2 = new Thread(MySlowFunction);
t2.IsBackground = true;
t2.Start();

# To resync after completion:
t1.Join();
t2.Join();

或者更好的是,使用 ThreadPool:

  ThreadPool.QueueUserWorkItem(MyWork);

记住处理线程异常。

I am not sure how Parallel.Invoke() decides what to execute in parallel, but if you want an assurance that they will execute in parallel, use threads:

var t1 = new Thread(MySlowFunction);
t1.IsBackground = true;
t1.Start();

var t2 = new Thread(MySlowFunction);
t2.IsBackground = true;
t2.Start();

# To resync after completion:
t1.Join();
t2.Join();

Or even better, use the ThreadPool:

  ThreadPool.QueueUserWorkItem(MyWork);

Remember to handle your thread exceptions.

无人问我粥可暖 2024-12-18 02:09:43

最简单的答案是使用 MSDN:Parallel.Invoke()

您还应该考虑:异步页面

The simplest answer is to use MSDN: Parallel.Invoke().

You should also consider: Asynchronous Pages.

娇妻 2024-12-18 02:09:43

尝试使用 System.Threading.Tasks 命名空间

类似

var task1 = Task.Factory.StartNew(() => DoA());
var task2 = Task.Factory.StartNew(() => DoB());
var task3 = Task.Factory.StartNew(() => DoC());
Task.WaitAll(task1, task2, task3);

http://www.codethinked.com/net -40-and-systemthreadingtasks

Try using System.Threading.Tasks namespace

Something like

var task1 = Task.Factory.StartNew(() => DoA());
var task2 = Task.Factory.StartNew(() => DoB());
var task3 = Task.Factory.StartNew(() => DoC());
Task.WaitAll(task1, task2, task3);

http://www.codethinked.com/net-40-and-systemthreadingtasks

猛虎独行 2024-12-18 02:09:43

下面是一个并行执行 4 个任务的示例:

public partial class _Default : System.Web.UI.Page
{
    public class MyViewModel
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }

    protected void Page_Load(object sender, EventArgs e)
    {

    }

    protected void BtnBindClick(object sender, EventArgs e)
    {
        // we define the input for the tasks: each element consists
        // of the grid we are willing to bind the results at the end and
        // some optional parameter we want to pass to the GetData function
        var inputs = new[] 
        { 
            new { Grid = gv1, Input = "Mill" }, 
            new { Grid = gv2, Input = "Factory" }, 
            new { Grid = gv3, Input = "Garage" }, 
            new { Grid = gv4, Input = "Master" }, 
        };

        // define the tasks we want to execute in parallel
        var tasks = inputs
            .Select(x => Task.Factory.StartNew(
                () => new { Grid = x.Grid, Output = GetData(x.Input) })
            )
            .ToArray();

        // define a task which will be executed once all tasks have finished
        var finalTask = Task.Factory.ContinueWhenAll(tasks, x => x);

        // wait for the final task
        finalTask.Wait();

        // consume the results
        foreach (var item in finalTask.Result)
        {
            if (item.Exception == null)
            {
                // if no exception was thrown for this task we could bind the results
                item.Result.Grid.DataSource = item.Result.Output;
                item.Result.Grid.DataBind();
            }
        }
    }

    private MyViewModel[] GetData(string input)
    {
        // Simulate slowness
        Thread.Sleep(1000);
        return Enumerable.Range(1, 5).Select(x => new MyViewModel
        {
            Id = x,
            Name = input
        }).ToArray();
    }
}

Here's an example which will execute the 4 tasks in parallel:

public partial class _Default : System.Web.UI.Page
{
    public class MyViewModel
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }

    protected void Page_Load(object sender, EventArgs e)
    {

    }

    protected void BtnBindClick(object sender, EventArgs e)
    {
        // we define the input for the tasks: each element consists
        // of the grid we are willing to bind the results at the end and
        // some optional parameter we want to pass to the GetData function
        var inputs = new[] 
        { 
            new { Grid = gv1, Input = "Mill" }, 
            new { Grid = gv2, Input = "Factory" }, 
            new { Grid = gv3, Input = "Garage" }, 
            new { Grid = gv4, Input = "Master" }, 
        };

        // define the tasks we want to execute in parallel
        var tasks = inputs
            .Select(x => Task.Factory.StartNew(
                () => new { Grid = x.Grid, Output = GetData(x.Input) })
            )
            .ToArray();

        // define a task which will be executed once all tasks have finished
        var finalTask = Task.Factory.ContinueWhenAll(tasks, x => x);

        // wait for the final task
        finalTask.Wait();

        // consume the results
        foreach (var item in finalTask.Result)
        {
            if (item.Exception == null)
            {
                // if no exception was thrown for this task we could bind the results
                item.Result.Grid.DataSource = item.Result.Output;
                item.Result.Grid.DataBind();
            }
        }
    }

    private MyViewModel[] GetData(string input)
    {
        // Simulate slowness
        Thread.Sleep(1000);
        return Enumerable.Range(1, 5).Select(x => new MyViewModel
        {
            Id = x,
            Name = input
        }).ToArray();
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文