任务没有等待完成,并且错误超时协议错误2504 [英] Task isn't waited to finish and error timeout protocol error 2504

查看:50
本文介绍了任务没有等待完成,并且错误超时协议错误2504的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有此构造函数的类:

I have a class with this constructor:

MyType01 _myData01;
MyType02 _myData02;
MyType03 _myData03;


public MyClass()
{
    getDataFromDataBase();


    //Code that use the data from database.
    string myText = _myData02.Property1; //error because my data02 is null.
}


private async void getDataFromDataBase()
{
    await myMethod01Async();
    await myMethod02Async();
    await myMethod03Async();
}

此代码在本地数据库中有效,但是当我连接到远程计算机上的数据库时,出现超时和协议2504错误.

This code works in a local database but when I connect to the database in a remote computer, I get an error of timeout and protocol 2504.

如果我进行调试,我会注意到,如果我在运行 myMethod01Asyc()的行中设置了一个断点,然后按"F5",则下一行代码是构造函数,尝试使用 _myData02 变量中的数据,但它仍为null,因为它没有完成方法 getMyData02Async().

If I debug, I can notice that if I set a break-point in the line that run myMethod01Asyc() and press "F5", the next line of code is the next line in the constructor which try to use the data in _myData02 variable, but it is still null because it is not finished the method getMyData02Async().

也许我是错的,但是我认为使用等待代码要等到方法完成之后,但就我而言,这不是行为,因为它会在构造函数中的下一行继续.

Perhaps I am wrong, but I thought that using await the code wait until the method is finished, but in my case it isn't the behaviour because it continues with the next line in the constructor.

那么我怎么能在构造函数中等到 getDataFromDataBase()完成才能使用我需要的数据?

So how could I wait in the constructor until getDataFromDataBase() is finished to can use the data that I need?

推荐答案

除事件处理程序外,避免 async void .

Avoid async void except for event handlers.

参考异步/等待-异步编程的最佳做法

我建议您创建一个事件处理程序并在那里等待任务.

I suggest you create an event handler and await you tasks there.

MyType01 _myData01;
MyType02 _myData02;
MyType03 _myData03;

public MyClass() {
    //subscribe to event
    LoadingData += OnLoadingData;
    //raise event
    LoadingData(this, EventArgs.Empty);
}

private event EventHandler LoadingData = delegate { };

private async void OnLoadingData(object sender, EventArgs args) {
    await getDataFromDataBase();
    //Code that use the data from database.
    string myText = _myData02.Property1; 
}

private async Task getDataFromDataBase() {
    await myMethod01Async();
    await myMethod02Async();
    await myMethod03Async();
}

请注意更改 getDataFromDataBase 以返回 Task ,以便可以等待它.

Note the change of getDataFromDataBase to return a Task so that it can be awaited.

这篇关于任务没有等待完成,并且错误超时协议错误2504的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆