gpt4 book ai didi

c# - 使用控制台或 WindowsService 的 AsyncOperation

转载 作者:太空宇宙 更新时间:2023-11-03 15:21:54 31 4
gpt4 key购买 nike

如何在控制台或 Windows Servie 项目中使用 AsyncOperation?

此方法适用于 Windows 窗体,但不适用于控制台和服务:

static void Bla2(object o)
{
//e.g. 10 but should be the same as mainId
//Works when using Windows Forms
int id = Thread.CurrentThread.ManagedThreadId;
}

static void Bla(object o)
{
int id = Thread.CurrentThread.ManagedThreadId; //e.g. 9 => always different from mainId

AsyncOperation asyncOp = (AsyncOperation)o;
asyncOp.Post(Bla2, null);
}

static void Main(string[] args)
{
int mainId = Thread.CurrentThread.ManagedThreadId; //e.g. 8
AsyncOperation asyncOp = AsyncOperationManager.CreateOperation(null);

Thread t = new Thread(new ParameterizedThreadStart(Bla));
t.Start(asyncOp);

...
}

这里有一个类似的问题 https://stackoverflow.com/questions/31494733/asyncoperation-to-raise-events-specially-in-class-libraries但没有得到任何答复。

我做错了什么?

我错过了什么吗?

最佳答案

根据您使用的 dot net 目标版本,我建议使用 async/await。这是对应用程序进行多线程处理的一种简单易行的方法,但请记住竞争条件和多线程开发的所有其他陷阱。

static task<int> async Bla2Async(object o)
{
return await WebClient.PostToWebAPIAsync(o);//Log time to complete. returns response code(int) from http response
}

static void Bla(object o)
{
var response = Bla2Async(o);
}

static void Main(string[] args)
{
Bla(new object());


...
}

这在 MSDN 上有概述 here .它概述了 async/await 关键字如何工作的所有细节。

关于c# - 使用控制台或 WindowsService 的 AsyncOperation,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37005931/

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