c# - 函数等待其他应用程序的响应

标签 c# wait sharing synchronous

我们正在致力于集成两个同时运行并共享数据的不同应用程序。一个应用程序提供数据,另一个应用程序根据外部系统和数据计算一些值,并且必须将其返回给第一个应用程序。

我们正在使用此库在应用程序之间共享数据:http://grouplab.cpsc.ucalgary.ca/cookbook/index.php/Toolkits/Networking

该库基本上允许创建一个可以由任何应用程序查询的共享字典(只要它知道共享字典的位置)。

因此,应该发生的情况是程序 A 必须向程序 B 提供一些数据,程序 B 使用这些数据并将其他一些数据返回给程序 A。

我的问题是如何让程序 A 等待 B 的响应。更具体地说,我可以将一个对象放入共享字典中,另一个程序收到字典更改的通知,它可以计算一些属性并更新字典中的对象。程序 A 可以收到通知,但我希望程序 A 等待,直到它返回此响应 - 程序 A 的操作应该基于返回的值。

我认为可以做到这一点的一个非常丑陋的方法是在函数内部有一个无限循环,它不断查询字典以查看对象是否已更新 - 如果它已跳出循环并使用该对象及其计算属性。有谁知道更好的解决方案?

最佳答案

使用他们的 subscription model ,你可以避免所有的无限循环。 当您唯一需要检查的时间是实际更新的时间时,为什么您需要循环?因为您订阅了字典中的关键模式,并且当适合该模式的关键时,您的连接将收到通知更新/添加,您只需要检查即可。

所以基本上,您可以使用 ManualResetEvent 来等待您自己的系统内的同步。以下是 ManualResetEvent 的使用示例:

using System;
using System.Threading;

class Program
{
    static void Main(string[] args)
    {
        //    create the reset event -- initially unsignalled
        var resetEvent = new ManualResetEvent(false);
        //    information will be filled by another thread
        string information = null;

        //    the other thread to run
        Action infoGet = delegate
        {
            //    get the information
            information = Console.ReadLine();
            //    signal the event because we're done
            resetEvent.Set();
        };

        //    call the action in a seperate thread
        infoGet.BeginInvoke(null, null);
        //    wait for completion
        resetEvent.WaitOne();
        //    write out the information
        Console.WriteLine(information);
    }
}

要转换为您的框架,您可能会让订阅处理程序检查更新的内容,找到等待句柄并向其发出信号,从而推进适当的等待线程。

关于c# - 函数等待其他应用程序的响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2107320/

相关文章:

c# - IdentityServer4 用户的声明未包含在 JWT 中且未发送到 Web Api

c++ - 如何删除对象之间的变量共享?

flutter - 是否可以通过 flutter app 共享您的位置

c# - 在 XOR 上为校验和添加值

c# - DateTime.Parse ("2012-09-30T23:00:00.0000000Z") 总是转换为 DateTimeKind.Local

c# - 在内容页面之间遍历时 cookie 值消失

linux - 服务器只接受一次并终止

java:为什么等待一段时间会使我的程序无法按顺序执行?

java - 增加 sleep /等待时间直到需要为止

file - 如何在Windows 7中映射ubuntu共享文件夹?