任务中的console.writeline不起作用

时间:2017-02-19 18:21:18

标签: c# multithreading httptaskasynchandler

我正在学习基于任务的aysny编程,无法使这段代码工作。控制台仅打印一次消息然后消失。

如果我删除了读取行并运行程序(不是调试模式),控制台就会出现,并显示消息说按一个键继续。当我调试并将调试器放入console.write时,它可以工作一段时间,然后控制台窗口消失并重新启动。如果我使用for循环< 10000而不是while,那么行为也是相同的

你能否告诉我我做错了什么。

static void Main(string[] args)
        {
            multitasker();

        }

       static async void   multitasker()
        {
            Task task1 = new Task(PrintMessageA);
            task1.Start();
            await task1;            
        }

        static void PrintMessageA()
        {
          while(true)
            {
                Console.WriteLine("Message from A");
                Console.ReadLine();

            }
        }

1 个答案:

答案 0 :(得分:2)

你的主线程没有阻塞,因此立即退出。在某种意义上你必须“等待所有的方式”并等待Option Explicit Dim FindRow As Range Private Sub Search_Click() Dim cRow As String On Error Resume Next cRow = Me.txtSearch.Value 'find the name of the employee written on the search box in column B Set FindRow = Sheets("Sheet1").Range("B:B").Find(what:=cRow, LookIn:=xlValues) If Not FindRow Is Nothing Then '<-- successful find 'add the values to the userform Me.txtname.Value = FindRow.Value Me.txtposition.Value = FindRow.Offset(0, 1).Value Me.txtlocation.Value = FindRow.Offset(0, 2).Value Me.txtbasicsalary.Value = FindRow.Offset(0, 3).Value End If End Sub '====================================================================== Sub UpdateInfo_Click() Dim fname As String Dim lname As String fname = Me.txtname.Text lname = Me.txtposition.Text If Not FindRow Is Nothing Then '<-- check if there was a successful find in the "Search" sub Sheets("Sheet1").Cells(FindRow.Row, 2).Value = fname Sheets("Sheet1").Cells(FindRow.Row, 3).Value = lname Set FindRow = Nothing '<-- clear after use End If End Sub ,但你实际上不能这样做,如后面所见。

首先,您在multitasker

中返回任务
multitasker

问题是您无法使static async Task multitasker() { Task task1 = new Task(PrintMessageA); task1.Start(); await task1; } (入口点)异步,因此您需要通过在返回的任务上调用Main()来阻止该线程

Wait()