【发布时间】:2018-09-29 21:35:12
【问题描述】:
我正在尝试创建一个函数,该函数在被调用时会将信息返回给服务器上的调用者。我在这个函数中想要的是,它创建一个向服务器发出命令的线程,然后将自身挂起,直到服务器返回答案。
public AccountState GetAccount(string key)
{
AccountState state = null;
Thread t = new Thread(() =>
{
_connection.SomeCommandSentToServer(key);
accountRequests.TryAdd(key, (Thread.CurrentThread, null));
//Suspend current thread until ServerReponseHere is called
Thread.CurrentThread.Suspend();
//We have been resumed, value should be in accountRequests now
accountRequests.TryRemove(key, out var item);
state = item.AccountState;
});
t.Start();
return state;
}
public ConcurrentDictionary<string, (Thread Thread, AccountState AccountState)> accountRequests = new ConcurrentDictionary<string, (Thread Thread, AccountState AccountState)>();
///Once server is done with processed command, call to this function made
public void ServerReponseHere(string key, AccountState state)
{
accountRequests.TryGetValue(username, out var item);
accountRequests.TryUpdate(username, (item.Thread, new AccountState()), item);
item.Thread.Resume();
}
我的想法是,在另一个函数中,当服务器响应时,它会调用上面显示的 ResumeThread 函数。
C# 说 Suspend / Resume 是已弃用的函数,但是 -- 有什么更好的方法来做到这一点?
更新
关于“SomeCommandSentToServer”的说明——这只是通过 TCP 套接字向服务器发送命令。
在那个调用中,真正发生的只是传输到服务器。我正在使用一个使用 WinSock2.h 调用“Send()”的库——是的,我知道它是一个已弃用的库……但我正在使用的库需要它。
我有一个单独的线程来轮询来自服务器的输入。所以我没有办法在这个 SomeCommandSentToServer 上“等待”——我需要等待某种回调函数(也就是我提到的恢复函数)——才能完成这项工作。
我不确定该怎么做
【问题讨论】:
-
看起来 async-await 是你的答案
-
您能否更具体地说明如何使用 Tasks 使其工作?
-
您如何获得您的
AccountState?_connection.SomeCommand似乎没有返回任何内容。 -
正如我所说的 -- SomeCommand -- 向服务器发出请求,然后服务器会在某个时候调用 ResumeThread() ---
-
async and await 正是针对这种情况制作的。
标签: c# multithreading async-await resume suspend