如何阻塞一个线程,直到另一个线程在 C# 中获得服务器响应

How to block a thread until another thread gets a server response in C#

我正在开发一个库,您可以在其中创建名称为服务器的服务器:

UtilityServer server = new UtilityServer("TestServer1", 3500);

您还可以使用以下名称创建客户端:

UtilityClient client = new UtilityClient("TestClient1");

服务器使用您选择的端口在本地计算机上创建套接字。服务器为运行时,客户端可以通过:

连接
client.Connect(ServerIP, 3500);

当我基于事件进行时一切正常,例如:

client.UserNamesArrived += OnUserNamesArrived;
client.RequestUserNames();

private void OnUserNamesArrived(ReadOnlyCollection<string> userNames)
{
    // Do something with userNames
}

但是当我尝试在我的库中创建一个阻塞方法时:

public ReadOnlyCollection<string> GetUserNames()
{
    // Request userNames from server
    // Wait until server sent us userNames
    // return userNames
}

// Running on seperate thread, gets messages that server sents to client
ReceiveMessages()
{
    while(_isConnected)
    {
    // Waits until message is received (_strReader.ReadLine())
    // Looks what message contains (Can also be other things then userNames)
    // Gets collection of userNames when message contains it (Working)
    // Triggers event 'UserNamesArrived' with userNames as argument
    }
}

我不知道怎么办。

现在这是我的问题,我如何在我的 GetUserNames-Thread 中等待,直到我的 ReceiveMessages-Thread 获得 userNames 的集合,我如何才能 return 它们?

.Net-Framework中也有类似的阻塞Thread的方法,例如:

sqlCommand.ExecuteNonQuery();

这也会阻止它并等待响应,但是如何?

您可以使用 .NET Framework 的 async 和 await 属性。您需要将 ReceiveMessages() 方法设置为异步任务,并使运行该方法的主线程 ReadOnlyCollection<string> GetUserNames() 等待 ReceiveMessages() 完成...我认为它会起作用。

public async ReadOnlyCollection<string> GetUserNames()
{
    // Request userNames from server
    List<UserNames> userNameList = await ReceiveMessages();
    // return userNames
}

// Running on seperate thread, gets messages that server sents to client
async Task<List<UserNames>> ReceiveMessages()
{
    // Looks what message contains
    // Gets collection of userNames when requested (Working)
    // Triggers event 'UserNamesArrived' with userNames as argument
}

看看那个例子:await and async example

考虑 System.Threading.WaitHandle 的实现之一。

我经常使用 AutoResetEvent 用于需要阻塞的跨线程通知。

AutoResetEvent allows threads to communicate with each other by signaling. Typically, you use this class when threads need exclusive access to a resource.

https://msdn.microsoft.com/en-us/library/system.threading.autoresetevent%28v=vs.110%29.aspx

由于信号性质,您经常会听到这种结构称为 信号量。 WaitHandles 是一项 OS 功能,因此请确保正确处理句柄。

WaitHandle 的显着特征是 WaitOne 方法。

WaitOneBlocks the current thread until the current WaitHandle receives a signal.