繁体   English   中英

ASP.NET-异步编程

[英]ASP.NET - async programming

我试图了解异步编程,但我有一个问题。 关于以下的功能。

public async void TestAsyncCall() {
Task<string> TaskResult1 = DoSomethingAsync();
string Result2 = DoSomething();
string Result1 = await TaskResult1; 
}

public string DoSomething() {
return "synch";
}

public async Task<string> DoSomethingAsync() {
await Task.Delay(10000);
return "asynch";
}

在函数TestAsyncCall()中,将使用一个线程执行DoSomethingAsync(),而使用另一个线程执行DoSomething()吗?

然后,当遇到等待时,它将等待DoSomethingAsync()完成并释放该线程(同时也不会阻塞原始线程)吗?

还是不保证会创建任何新线程? 在那种情况下,DoSomethingAsync调用仅在处理某些外部资源时才有意义吗?

我建议您阅读有关async ASP.NET的文章。

还是不保证会创建任何新线程?

这不会创建任何新线程。 特别是, asyncawait本身不会创建任何新线程。

在ASP.NET,很可能是在之后的代码await会在不同的线程比之前的代码运行await 不过,这只是将一个线程交换为另一个线程。 没有创建新线程。

在那种情况下,DoSomethingAsync调用仅在处理某些外部资源时才有意义吗?

async的主要用例是处理I / O,是的。 在ASP.NET上尤其如此。

正如@ Stepehen-cleary所说:“尤其是,异步和等待本身不会创建任何新线程。”

下一个示例摘自John Skeet的《深度的C锐利》一书,第15章第465页:

class AsyncForm : Form
{
    /* The first part of listing 15.1 simply creates the UI and hooks up an event handler for
       the button in a straightforward way */
    Label label;
    Button button;
    public AsyncForm()
    {
        label = new Label { 
                            Location = new Point(10, 20),
                            Text = "Length" 
                          };
        button = new Button {
                                Location = new Point(10, 50),
                                Text = "Click" 
                            };  

        button.Click += DisplayWebSiteLength;
        AutoSize = true;
        Controls.Add(label);
        Controls.Add(button);
    }   


    /*  When you click on the button, the text of the book’s home page is fetched
        and the label is updated to display the HTML lenght in characters */
    async void DisplayWebSiteLength(object sender, EventArgs e)
    {
        label.Text = "Fetching...";
        using (HttpClient client = new HttpClient())
        {
            string text =
            await client.GetStringAsync("http://csharpindepth.com");
            label.Text = text.Length.ToString();
        }
    }
    /*  The label is updated to display the HTML length in characters D. The
        HttpClient is also disposed appropriately, whether the operation succeeds or fails—
        something that would be all too easy to forget if you were writing similar asynchronous
        code in C# 4  */
}

考虑到这一点,让我们看一下您的代码,您拥有Result1和Result2,让一个异步任务等待同步任务完成是没有意义的。 我将使用Parallelism,因此您可以执行这两种方法,但要返回类似两组数据的内容,同时执行LINQ查询。

看一下有关异步任务并行的这个简短示例:

public class StudentDocs 
{

    //some code over here

    string sResult = ProcessDocs().Result;

    //If string sResult is not empty there was an error
    if (!sResult.Equals(string.Empty))
        throw new Exception(sResult);

    //some code over there


    ##region Methods   

    public async Task<string> ProcessDocs() 
    {
        string sResult = string.Empty;

        try
        {
            var taskStuDocs = GetStudentDocumentsAsync(item.NroCliente);
            var taskStuClasses = GetStudentSemesterClassesAsync(item.NroCliente, vencimientoParaProductos);

            //We Wait for BOTH TASKS to be accomplished...
            await Task.WhenAll(taskStuDocs, taskStuClasses);

            //Get the IList<Class>
            var docsStudent = taskStuDocs.Result;
            var docsCourses = taskStuClasses.Result;

           /*
                You can do something with this data ... here
            */
        }
        catch (Exception ex)
        {
            sResult = ex.Message;
            Loggerdb.LogInfo("ERROR:" + ex.Message);
        }
    }

    public async Task<IList<classA>> GetStudentDocumentsAsync(long studentId)
    {
        return await Task.Run(() => GetStudentDocuments(studentId)).ConfigureAwait(false);
    }

    public async Task<IList<classB>> GetStudentSemesterCoursessAsync(long studentId)
    {
        return await Task.Run(() => GetStudentSemesterCourses(studentId)).ConfigureAwait(false);
    }

    //Performs task to bring Student Documents
    public IList<ClassA> GetStudentDocuments(long studentId)
    {
        IList<ClassA> studentDocs = new List<ClassA>();

        //Let's execute a Stored Procedured map on Entity Framework
        using (ctxUniversityData oQuery = new ctxUniversityData())
        {
            //Since both TASKS are running at the same time we use AsParallel for performing parallels LINQ queries
            foreach (var item in oQuery.GetStudentGrades(Convert.ToDecimal(studentId)).AsParallel())
            {
                //These are every element of IList
                studentDocs.Add(new ClassA(
                    (int)(item.studentId ?? 0),
                        item.studentName,
                        item.studentLastName,
                        Convert.ToInt64(item.studentAge),
                        item.studentProfile,
                        item.studentRecord
                    ));
            }
        }
        return studentDocs;
    }

    //Performs task to bring Student Courses per Semester
    public IList<ClassB> GetStudentSemesterCourses(long studentId)
    {
        IList<ClassB> studentCourses = new List<ClassB>();

        //Let's execute a Stored Procedured map on Entity Framework
        using (ctxUniversityData oQuery = new ctxUniversityData())
        {
            //Since both TASKS are running at the same time we use AsParallel for performing parallels LINQ queries
            foreach (var item in oQuery.GetStudentCourses(Convert.ToDecimal(studentId)).AsParallel())
            {
                //These are every element of IList
                studentCourses.Add(new ClassB(
                    (int)(item.studentId ?? 0),
                        item.studentName,
                        item.studentLastName,
                        item.carreerName,
                        item.semesterNumber,
                        Convert.ToInt64(item.Year),
                        item.course ,
                        item.professorName
                    ));
            }
        }
        return studentCourses;
    }

    #endregion
}

用于

[英]use of <!— # in HTML or ASP.net programming

暂无
暂无

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

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