使用Console或WindowsService的AsyncOperation

时间:2016-05-03 13:42:10

标签: c# asynchronous

如何在Console或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 但没有得到任何答案。

我做错了什么?

我错过了吗?

1 个答案:

答案 0 :(得分:0)

根据您使用的点网目标版本,我建议使用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关键字如何工作的所有细节。