创建一个新的参数化线程

发布于 2024-10-29 22:57:16 字数 450 浏览 2 评论 0原文

我想在不同的线程中运行我的函数,但问题是该函数需要参数。

如果我用不需要参数的函数(CPUPlay())尝试它,那就可以了:

private void OpenNewThread(bool open)
    {
        Thread thread = new Thread(new ThreadStart(CPUPlay));
    }

但是如果我用需要参数的函数尝试它,它不起作用:

private void OpenNewThread(bool open)
{
    Thread thread = new Thread(new ParameterizedThreadStart(CloseOpenAnimation));
    thread.Start(open);
}

那么我如何运行带有参数的函数不同的线程?

I want to run my function in a different thread but the problem is that the function needs a paramater.

If I try it with a function that doesn't need paramters(CPUPlay()) its ok:

private void OpenNewThread(bool open)
    {
        Thread thread = new Thread(new ThreadStart(CPUPlay));
    }

But if I try it with a function that needs parameters, it doesn't work:

private void OpenNewThread(bool open)
{
    Thread thread = new Thread(new ParameterizedThreadStart(CloseOpenAnimation));
    thread.Start(open);
}

So how can I run a function with parameters in a different thread?

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

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

发布评论

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

评论(3

番薯 2024-11-05 22:57:16

你的函数与这个签名匹配吗?

public void CloseOpenAnimation(object argument)

Does your function match this signature?

public void CloseOpenAnimation(object argument)
渔村楼浪 2024-11-05 22:57:16

欺骗和利用代表

private void OpenNewThread(bool open)
{
    Thread thread = new Thread(new ThreadStart(
        () => CloseOpenAnimation(open)));
    thread.Start();
}

Cheat and use delegates

private void OpenNewThread(bool open)
{
    Thread thread = new Thread(new ThreadStart(
        () => CloseOpenAnimation(open)));
    thread.Start();
}
桃气十足 2024-11-05 22:57:16

尝试BackgroundWorker对象。您可以使用一个对象参数 Argument。

BackgroundWorker bg = new BackgroundWorker();
bg.DoWork+=new DoWorkEventHandler(bg_DoWork);
bg.RunWorkerAsync(5);

static void  bg_DoWork(object sender, DoWorkEventArgs e)
{
            int j = (int)e.Argument;
}

其中 e.Argument 是对象类型。

Try BackgroundWorker object. There is an object parameter Argument you can use.

BackgroundWorker bg = new BackgroundWorker();
bg.DoWork+=new DoWorkEventHandler(bg_DoWork);
bg.RunWorkerAsync(5);

static void  bg_DoWork(object sender, DoWorkEventArgs e)
{
            int j = (int)e.Argument;
}

where e.Argument is of type object.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文