从多个线程等待任务

时间:2015-06-28 06:09:22

标签: c# task

是否可以同时从两个不同的线程在同一个import java.util.*; public class CardDescription { public static void main(String[] args) { Card c1 = new Card("KS"); System.out.println("Your card is" + c1.getDescription()); }} public class Card { private String value; private String suite; private String string1; private String string2; public Card(String s1){ value = s1.substring(0, 1); suite = s1.substring(1); } public String getDescription(){ if (value.equalsIgnoreCase("A")){ string1 = "Ace"; } else if(value.equalsIgnoreCase("K")){ string1 = "King"; } else if(value.equalsIgnoreCase("Q")){ string1 = "Queen"; } else if(value.equalsIgnoreCase("J")){ string1 = "Jack"; } else if(value.equals("10")){ string1 = "Ten"; } else if(value.equals("9")){ string1 = "Nine"; } else if(value.equals("8")){ string1 = "Eight"; } else if(value.equals("7")){ string1 = "Seven"; } else if(value.equals("6")){ string1 = "Six"; } else if(value.equals("5")){ string1 = "Five"; } else if(value.equals("4")){ string1 = "Four"; } else if(value.equals("3")){ string1 = "Three"; } else if(value.equals("2")){ string1 = "Two"; } if(suite.equalsIgnoreCase("D")){ string2 = "Diamonds"; } else if(suite.equalsIgnoreCase("H")){ string2 = "Hearts"; } else if(suite.equalsIgnoreCase("S")){ string2 = "Spades"; } else if(suite.equalsIgnoreCase("C")){ string2 = "Clubs"; } return string1 + " of " + string2; } } 上调用Wait()

例如,以下代码是否有效:

Task

动机:
我实现了一个控制器,它最终将请求序列化到串口,并处理来自端口的通知。请求可以从不同的线程发送,它们应该能够等待结果(或异常),但可以选择异步工作。

我考虑上面的设计,因为private BlockingCollection<Task> _queue = new BlockingCollection<Task>(); private Thread _taskPumpThread; ... private void Run() { _taskPumpThread= new Thread(() => TaskPump(...)); _taskPumpThread.Start(); DoNothing(); } private void DoNothing() { Task doNothing = new Task(() => Console.WriteLine("Doing nothing")); queue.Add(doNothing); doNothing.Wait(); // no try-catch for brevity } private void TaskPump(CancellationToken token) { while (!token.IsCancellationRequested) { Task task = queue.Take(); task.Start(); task.Wait(); } } 可以很好地处理所有情况(同步结果,异步调用和异常)。

可以找到相关但不相同的问题here

1 个答案:

答案 0 :(得分:6)

我会限制自己回答你非常具体的问题。

如果您运行以下简短程序,您会看到答案是,您可以让多个线程等待同一任务:

public static void Main(string[] args)
{
    Task t = Task.Delay(10000);
    new Thread(() => { ThreadRun(t); }).Start();
    new Thread(() => { ThreadRun(t); }).Start();
    Console.WriteLine("Main thread exits"); // this prints immediately.
}

private static void ThreadRun(Task t)
{
    t.Wait();
    Console.WriteLine(Thread.CurrentThread.ManagedThreadId + " finished waiting"); // this prints about 10 seconds later.
}