从异步方法调用异步方法将关闭应用程序

时间:2018-11-03 15:12:46

标签: c# asynchronous async-await synchronization

我有一个异步方法(我们称它为Initialize()),它使用await启动其他各种方法。

Initialize()以阻塞方式调用。我的教授告诉我,我应该通过创建InitializeAsync()方法使这个Initialize()方法也异步。因此,我的InitializeAsync()方法现在使用async和await调用Initialize(),而我的Initialize()方法也使用async和await。

问题:我不知道为什么,但是我的程序开始运行,但是立即关闭,而不是等待Initialize()。有什么想法我做错了吗?

public Client(string ipAddress, int port, string name)
    {
        this.username = name;
        this.port = port;
        this.ipAddress = ipAddress;
        this.status = Status.WAIT;

        this.InitializeAsync();
    }

private async void InitializeAsync()
    {
        await Initialize();
    }

private async Task Initialize()
    {
        this.users = new List<User>();

        this.SetupListenSocket();

        // Starting the listener.
        Task listenerTask = new Task(ListenEndless);
        listenerTask.Start();

        this.SetupSendSocket();

        // Starting the useriput sending.
        Task sendingTask = new Task(SendEndlessUserinputs);
        sendingTask.Start();

        string heloMessage = "cf-1.0:HELO:" + this.username;

        // Sending the helo message.
        this.SendMessage(heloMessage);

        // Starting the endless ping sender.
        Task pingTask = new Task(SendPingEndless);
        pingTask.Start();

        await listenerTask;
        await sendingTask;
        await pingTask;

        Console.WriteLine("\nDone.");
        Console.ReadKey();
    }

0 个答案:

没有答案