gpt4 book ai didi

c# - 方法在单独的线程中运行 - 如何在调用线程中检索其值

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

我有返回一些数据类型的方法

MyType MyMethod()

如果我将此方法运行到一个单独的线程中,如何在调用线程(调用其他线程执行 MyMethod)中检索此返回类型?

最佳答案

有很多种方法,这里是一个:

Func<MyType> func = MyMethod;
func.BeginInvoke(ar =>
{
MyType result = (MyType)func.EndInvoke(ar);
// Do something useful with result
...
},
null);

这是另一个,使用 Task API:

Task.Factory
.StartNew(new Func<MyType>(MyMethod))
.ContinueWith(task =>
{
MyType result = task.Result;
// Do something useful with result
...
});

最后一个,使用异步 CTP(C# 5 预览版):

MyType result = await Task.Factory.StartNew<MyType>(MyMethod);
// Do something useful with result
...

关于c# - 方法在单独的线程中运行 - 如何在调用线程中检索其值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5970976/

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