簡體   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