如何使用任务显示延迟文本 [英] Howto use a task to display a delayed text

查看:98
本文介绍了如何使用任务显示延迟文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用C#5.0中的Task.Run进行一些简单的测试。我创建了一个带有按钮和标签的表单来测试它。应该很简单,但到目前为止还不能正常工作。



如何在不阻止ui的情况下延迟写入标签?



这是我的示例代码:

I'am doing some simple tests with Task.Run in C# 5.0. I have created a Form with a button and label to test it. Should be quite simple, but couldn't get it work so far.

How can i write delayed into the label without blocking the ui ?

Here is my sample code:

private void Button_Click(object sender, EventArgs e)
{
    writeStatus("test 1");
}

private Task taskWriteStatus(string text)
{
    return Task.Run (() =>
    {
        labelWrite(text);
    }); 
}

private void labelWrite(string text)
{
    Task.Delay(300).Wait();
    label1.Text = text;
}

private async void writeStatusAsync (string text)
{
    await taskWriteStatus(text);
}





我的尝试:



我做了一些研究,发现了解决这个问题的不同方法就像这篇好文章一样:

https://blog.imaginea.com/elegant-c-asynchrony/

推荐答案

您好,您无法直接访问UI线程另一个线程,UI线程具有最高优先级。您需要使用调度程序来执行此操作。



只需更改 labelWrite(字符串文本)方法,

Hi, You cannot access UI thread straight away from another thread, UI thread has highest priority. You need to use dispatcher to do it.

just change your labelWrite(string text) method,
private void labelWrite(string text)
{
    Task.Delay(10000).Wait();
    this.Invoke(new MethodInvoker(delegate ()
    {
        label1.Text = text;
    }));
}



并在Button Click中调用此方法。当您需要从线程更新UI时,请始终尝试使用调度程序。


And call this method in Button Click. Always try to use dispatcher when you need to update UI from threads.


这篇关于如何使用任务显示延迟文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆