简体   繁体   English

Task.Run 出现异步方法错误

[英]Task.Run with async method errors

i have button1_click method like this我有这样的 button1_click 方法

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


        Task<string> st1 = Task.Run(() => ReadFromFile());
        textBox1.AppendText("sdsadsa");
        textBox1.Text = st1.Result;



    }

i want to read from text file with ReadFromFile()我想用 ReadFromFile() 从文本文件中读取

Note: ReadFromFile is marked with async because i want to use async and await in this method注意:ReadFromFile 标记为 async 因为我想在此方法中使用 async 和 await

to planning some Task methods计划一些任务方法

but my Ui is freezing after append text method calling in line 2 in my button1_click method但是在我的 button1_click 方法的第 2 行中调用 append 文本方法后,我的 Ui 冻结了

and wait the result and show it in text box.并等待结果并将其显示在文本框中。

i want to throw the ReadFromFile method in task and await it without ui freezing我想在任务中抛出 ReadFromFile 方法并等待它而不冻结 ui

i tried many things like replacing line 1 with this我尝试了很多事情,比如用这个替换第 1 行

Task<string> st1 = await Task.Factory.StartNew(() => ReadFromFile());

with this, ui dont freeze but it skips line 2 the append method, i dont know why this skiping?有了这个,用户界面不会冻结,但它会跳过第 2 行 append 方法,我不知道为什么会这样跳过?

Just await ReadFromFile:只需await ReadFromFile:

private async void button1_Click(object sender, EventArgs e)
{
    string st1 = await ReadFromFile();
    textBox1.AppendText("sdsadsa");
    textBox1.AppendText(st1);
}

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

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