我正在研究 WCF 服务/客户端,试图弄清楚如何用不会阻塞调用者线程的东西替换 ManualResetEvent。
最重要的是在事件被触发await client.CloseAsync()
之前不会被调用。FinishedEventReceived
我看过使用TaskCompletionSource但我有点不确定在这种情况下它会如何工作。
我知道代码有点难看,完全违背了使用异步编程的目的,我的道歉。
有任何想法吗?
private async Task CallServiceMethodAndWaitForEvent()
{
var mre = new ManualResetEvent(true);
var client = new AwesomeClient();
client.FinishedEventReceived += (s, e) =>
{
// Do something with the result, this event is only fired once.
mre.Set();
};
client.UpdateEventReceived += (s, e) =>
{
// This even can fire several times before the finished event.
};
try
{
var parameters = new Parameters()
{
SomeParameter = "Test123",
TestAmount = 10000,
};
var errors = await client.DoWorkAsync(parameters);
Debug.WriteLine(errors);
mre.WaitOne(TimeSpan.FromSeconds(20));
await client.CloseAsync();
}
catch (FaultException ex)
{
}
catch (Exception)
{
client.Abort();
}
}