如何从事件处理程序调用异步方法?

huangapple go评论58阅读模式
英文:

How to call async method from an event handler?

问题

I am a complete beginner with async/await, so any help would be great.

async Task<bool> IsIPBannedAsync(string ip)
{
    try
    {
        bool isBanned = false;

        await foreach (var line in File.ReadLinesAsync(BannedIPFile))
        {
            if (line.Contains(ip.Trim())) { isBanned = true; break; }
        }
        return isBanned;
    }
    catch { return false; }
}

I call that from a button to send the result to a label:

private void btnCheck_Click(object sender, EventArgs e)
{
    lblResult.Text = string.Empty;

    lblResult.Text = IsIPBannedAsync(txtIP.Text);
}

Of course I have attempted to send the results using Convert.ToBoolean() | Convert.ToString() without success and get a System.Threading string rather than a boolean true | false.

Without async, I can get things to work:

bool isBanned = false;
isBanned = File.ReadLines(BannedIPFile).Contains(ip.Trim());
return isBanned;

Can anyone tell me what I am doing wrong, please?

Appreciate it - thank you

UPDATE:

Those of you who cannot find what I posted, you can see it here. I am using net core 7.0, in which it was introduced.

In the Button Click event, it doesn't like returning a boolean and asks for it to be converted to a string. All Microsoft solutions do not work.

If I change Task<bool> to Task<string> and then use return IsBanned.ToString(); everywhere it works.

@ProgrammingLlama, I used VB since version 3 and went to most of the .NET launches at Microsoft but since around 2010, I haven't really bothered with coding at all, yet I still pay the money for my MSDN Enterprise Subscription each year, as a single person.

My VS version:

Microsoft Visual Studio Enterprise 2022 (64-bit) - Current
Version 17.5.4

Some of my questions to the developer community of VS2022 have been referenced on this site many, many times as well as the MSDN site, back in the day.

The ReadAllLinesAsync comment is correct because why read a file all the way through if the answer is on line 1?

EDIT / UPDATE 2:

Liam, it is C#, Net Core 7 Desktop app, which will be put into a DLL and used on my friend's net core 7.0 razor website. I will be using this almost daily

Thank you to everyone for posting and I still have to work this out.

英文:

I am a complete beginner with async/await, so any help would be great.

    async Task&lt;bool&gt; IsIPBannedAsync(string ip)
    {
        try
        {
            bool isBanned = false;

            await foreach (var line in File.ReadLinesAsync(BannedIPFile))
            {
                if(line.Contains(ip.Trim())) { isBanned = true; break; }
            }
            return isBanned;
        }
        catch { return false; }
    }

I call that from a button to send the result to a label:

    private void btnCheck_Click(object sender, EventArgs e)
    {
        lblResult.Text = string.Empty;

        lblResult.Text = IsIPBannedAsync(txtIP.Text);
    }

Of course I have attempted to send the results using Convert.ToBoolean() | Convert.ToString() without success and get a System.Threading string rather than a boolean true | false.

Without async, I can get things to work:

    bool isBanned = false;
    isBanned = File.ReadLines(BannedIPFile).Contains(ip.Trim());
    return isBanned;

Can anyone tell me what I am doing wrong, please?

Appreciate it - thank you

UPDATE:

Those of you who cannot find what I posted, you can see it here. I am using net core 7.0, in which it was introduced.

In the Button Click event, it doesn't like returning a boolean and asks for it to be converted to a string. All Microsoft solutions do not work.

If I change Task&lt;bool&gt; to Task&lt;string&gt; and then use return IsBanned.ToString(); everywhere it works.

@ProgrammingLlama, I used VB since version 3 and went to most of the .NET launches at Microsoft but since around 2010, I haven't really bothered with coding at all, yet I still pay the money for my MSDN Enterprise Subscription each year, as a single person.

My VS version:

Microsoft Visual Studio Enterprise 2022 (64-bit) - Current
Version 17.5.4

Some of my questions to the developer community of VS2022 have been referenced on this site many, many times as well as the MSDN site, back in the day.

The ReadAllLinesAsync comment is correct because why read a file all the way through if the answer is on line 1?

EDIT / UPDATE 2:

Liam, it is C#, Net Core 7 Desktop app, which will be put into a DLL and used on my friend's net core 7.0 razor website. I will be using this almost daily

Thank you to everyone for posting and I still have to work this out.

答案1

得分: 1

以下是您要翻译的内容:

大家好,感谢大家提供的所有建议。我觉得这就像点击事件一样容易,这里

简而言之:

private async void btnCheck_Click(object sender, EventArgs e)
{

    bool IsBanned = await IsIPBannedAsync(txtIP.Text);

    lblResult.Text = IsBanned.ToString();

}

public async Task<bool> IsIPBannedAsync(string ip)
{
    try
    {
        bool IsBanned = false;

        await foreach (var line in File.ReadLinesAsync(IPFileList))
        {
            if (line.Contains(ip.Trim())) { IsBanned = true; break; }
        }
        return IsBanned;
    }
    catch { return false; } // 这是为了方便而做的。
}

是的,它编译通过。

[1]: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/async


<details>
<summary>英文:</summary>

Hi Everyone and thank you for all your suggestions. I found it as easy as the click event, [here][1].

In short:

    private async void btnCheck_Click(object sender, EventArgs e)
    {

        bool IsBanned = await IsIPBannedAsync(txtIP.Text);

        lblResult.Text = IsBanned.ToString();

    }

    public async Task&lt;bool&gt; IsIPBannedAsync(string ip)
    {
        try
        {
            bool IsBanned = false;

            await foreach (var line in File.ReadLinesAsync(IPFileList))
            {
                if (line.Contains(ip.Trim())) { IsBanned = true; break; }
            }
            return IsBanned;
        }
        catch { return false; } // This was done for ease here.
    }

and yes, it compiles.

  [1]: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/async

</details>



huangapple
  • 本文由 发表于 2023年4月11日 13:18:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/75982605.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定