gpt4 book ai didi

C# - 在线程中使用带有 "out"参数的函数

转载 作者:行者123 更新时间:2023-11-30 13:19:41 25 4
gpt4 key购买 nike

我有以下功能,我想在 System.Threading.Thread 中使用它:

private void tempFunction(int num, out string fullname, out string info)
{
// Doing a very long scenario.
// When finished, send results out!
fullname = result1;
info = result2;
}

我尝试在 (button_Click) 事件处理程序中使用以下代码:

private void submit_Button_Click(object sender, RoutedEventArgs e)
{
string Fullname = string.Empty, Info = string.Empty;
int index = 132;

Thread thread = new Thread(() => tempFunction(index, out Fullname, out Info));
thread.Start();
thread.Join();

// I always use "MessageBox" to check if what I want to do was done successfully
MessageBox.Show(Fullname + "\n" + Info);
}

你可以看到我使用了 thread.Join(); 因为我需要等到 Thread 完成才能获得线程进程的结果。

但上面的代码似乎不起作用,它只是卡住,我不知道为什么!

所以我肯定做错了什么,你能告诉我如何做我想做的事吗?

最佳答案

程序卡住的事实与out 参数没有任何关系。

程序卡住是因为您调用了 Thread.Join(),它基本上是这样写的:“阻塞调用线程,直到我完成处理”。因为调用线程是 UI 线程,所以 UI 卡住了。

有很多方法可以解决这个问题,其中最吸引人的是使用 await 关键字 (C# 5),但考虑到对 NET 4.5 的依赖,您可以选择附加一个继续改为手动:

Task.Factory.StartNew(() => tempFunction(index, out Fullname, out Info))
.ContinueWith(r => MessageBox.Show(Fullname + "\n" + Info));

(您需要以 .NET 4.0 为目标才能使用 Task 类。)

如果您受限于该框架的早期版本,那么下一个最佳解决方案可能是使用 BackgroundWorker 组件,因为您看起来正在使用一个Windows 窗体应用程序。

关于C# - 在线程中使用带有 "out"参数的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18167954/

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