简体   繁体   English

C# 剃刀任务<string>异步不工作

[英]C# Razor Task<string> async not working

So unfortunately I'm dealing with a C# Razor Web-forms (NOT MVC) web application.所以不幸的是,我正在处理一个 C# Razor Web 表单(非 MVC)Web 应用程序。

I was given a C# program with a class consisting of async functions that I need to make work on a cshtml page and I cannot figure out how...我得到了一个 C# 程序,其中包含一个由异步函数组成的类,我需要在 cshtml 页面上工作,但我不知道如何...

The two functions below are from a C# class that worked well with a C# Forms application.下面的两个函数来自一个 C# 类,该类与 C# 表单应用程序配合得很好。 (Notice that "TextBox1" is assigned the text). (注意“TextBox1”被分配了文本)。

My problem is that I need the string variable "xml" to be displayed on a cshtml page (preferably in a "textarea" element) and I cannot seem to call the showData() function to retrieve the value我的问题是我需要在 cshtml 页面上显示字符串变量“xml”(最好在“textarea”元素中)并且我似乎无法调用 showData() 函数来检索值

Can anyone help?任何人都可以帮忙吗?

 public static async void showData(string gID)
{
    string xml = "";
    try
    {
       xml = await WaitAsynchronouslyAsync(gID);
       //The original code set a TEXTBOX to the string value
       //I need to revise this code so that I can display it on a cshtml page
       TextBox1.Text = xml;

    }
    catch (HttpRequestException)
    {
        throw new ApplicationException("Could not connect to the server");
    }       
}


public static async Task<string> WaitAsynchronouslyAsync(string gID)
{
    await Task.Delay(10);
    urlLink = "*** A custom Intranet URL ***";
    ....
    ....
    ** preparing a Token/Client response url **
    ....
    ....
    string result = await serviceClient.GetStringAsync(urlLink);
    return result;
}

I've tried to bypass the void function and access the Task<string> function, but I cannot convert a Task<string> to a string value.我试图绕过void函数并访问Task<string>函数,但我无法将Task<string>转换为string值。

async void is difficult to work with to begin with, and even more so on ASP.NET . async void就很难处理,在 ASP.NET 上更是如此

I've tried to bypass the void function and access the Task function我试图绕过 void 函数并访问 Task 函数

Or just change async void showData to async Task showData - just as long as you avoid async void , you'll get to the same place.或者只是将async void showData更改为async Task showData - 只要您避免async void ,您就会到达同一个地方。

but I cannot convert a Task to a string value.但我无法将 Task 转换为字符串值。

You do this with await :你用await做到这一点:

var xml = await WaitAsynchronouslyAsync(gID);

or:或者:

await showData(gID);

Your calling function will need to be marked async and return Task / Task<T> .您的调用函数需要被标记为async并返回Task / Task<T> Yes, this does cause async / await to "grow" through your code base, and yes, this is both normal and necessary.是的,这确实会导致async / await在您的代码库中“增长”,是的,这既正常又必要。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM