gpt4 book ai didi

c# - 线程完成后如何调用函数?

转载 作者:太空宇宙 更新时间:2023-11-03 20:55:00 26 4
gpt4 key购买 nike

我尝试在线程结束后调用一个函数,但我不能。我只能在我的函数调用代码之前使用 while(threadName.isAlive) 方法,但它不好因为当我使用它时程序停止代码 。你知道吗?

public partial class Form1 : Form
{
Thread myThread;
string myString = string.Empty;

public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)
{
myThread = new Thread(write);
myThread.Start();
while (myThread.IsAlive) ;
textBox1.Text = myString;
}

public void write()
{
for (int i = 0; i < 10; i++) {

myString += "aaa " + i + "\r\n";
Thread.Sleep(1000);
}
}
}

最佳答案

如果您必须附加到Thread而不是Task,那么您可以启动一个任务来等待线程退出,然后然后运行一些额外的代码,如下所示:

using System;
using System.Threading;
using System.Threading.Tasks;

namespace Demo
{
static class Program
{
static void Main()
{
Thread thread = new Thread(work);
thread.Start();

Task.Run(() =>
{
thread.Join();
Console.WriteLine("Run after thread finished");
});

Console.ReadLine();
}

static void work()
{
Console.WriteLine("Starting work");
Thread.Sleep(1000);
Console.WriteLine("Finished work");
}
}
}

但是,现代的方法是使用 Taskawaitasync

例如:

async void button1_Click(object sender, EventArgs e)
{
textBox1.Text = "Awaiting task";
await writeAsync();
textBox1.Text = "Task finished";
}

Task writeAsync()
{
return Task.Run(() => write());
}

void write()
{
Thread.Sleep(10000);
}

如果您尝试第二种方法,您会看到 UI 保持响应,同时文本框显示“等待任务”。

另请注意,通常您希望阻止用户在等待任务时再次按下按钮,以避免运行多个任务。最简单的方法是在任务处于事件状态时禁用按钮,如下所示:

async void button1_Click(object sender, EventArgs e)
{
button1.Enabled = false;

textBox1.Text = "Awaiting task";
await writeAsync();
textBox1.Text = "Task finished";

button1.Enabled = true;
}

关于c# - 线程完成后如何调用函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51438468/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com