简体   繁体   English

如何使用并行任务在单独的线程中运行带参数的方法

[英]How to run method with arguments in separate thread using Parallel Tasks

here is sample of code for 这是代码示例

private void MethodStarter()
{
Task myFirstTask = Task.Factory.StartNew(Method1);
Task mySecondTask = Task.Factory.StartNew(Method1);
}

private void Method1()
{
 // your code
}

private void Method2()
{
 // your code
}

i am looking for code snippet for Parallel Tasks by which i can do the callback and pass argument to function also. 我正在寻找并行任务的代码片段,通过它我可以进行回调并将参数传递给函数。 can anyone help. 有谁可以帮忙。

If I understood your question right this might be the anwser: 如果我理解你的问题,这可能是一个问题:

private void MethodStarter()
{
    Task myFirstTask = Task.Factory.StartNew(() => Method1(5));
    Task mySecondTask = Task.Factory.StartNew(() => Method2("Hello"));
}

private void Method1(int someNumber)
{
     // your code
}

private void Method2(string someString)
{
     // your code
}

If you want to start all the threads at the same time you can use the example given by h1ghfive. 如果要同时启动所有线程,可以使用h1ghfive给出的示例。

UPDATE: An example with callback that should work but I haven't tested it. 更新:一个回调的例子应该可以工作,但我还没有测试过。

private void MethodStarter()
{
    Action<int> callback = (value) => Console.WriteLine(value);
    Task myFirstTask = Task.Factory.StartNew(() => Method1(5, callback));
    Task mySecondTask = Task.Factory.StartNew(() => Method2("Hello"));
}

private void Method1(int someNumber, Action<int> intCallback)
{
     // your code
     intCallback(100); // will call the call back function with the value of 100
}

private void Method2(string someString)
{
     // your code
}

You can alos look at Continuation if you don't want to pass in callback functions. 如果您不想传递回调函数,也可以查看Continuation

You should try something like this instead : 你应该尝试这样的事情:

Parrallel.Invoke(
  () => Method1(yourString1),
  () => Method2(youString2));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM