【发布时间】:2017-11-26 11:30:59
【问题描述】:
我正在编写一个代码,该代码定期截取网页的图像,扫描图像的像素颜色,如果找到颜色,则异步连接到 Web API。
我已经弄清楚了如何分别进行颜色扫描和连接,现在我必须加入这两个逻辑,但我不确定最好的方法。
扫描网页/图片扫描码本质上是这样的:
static void Main(string[] args)
{
while (true)
{
try
{
System.Threading.Thread.Sleep(5000); //refresh speed
string color = ReadColor(driver, webElement);
if (color== "blue")
{
//should connect for blue case and run the Blue() function below
}
if (color== "green")
{
//should connect for green case
}
}
catch
{
}
}
}
HttpClient 连接是这样的:
static HttpClient client = new HttpClient();
static void Main()
{
RunAsync().Wait();
}
static async Task RunAsync()
{
client.BaseAddress = new Uri("website");
Data data = new Data { };
try
{
data = await Green();
data = await blue(); //functions to run depending on color
}
catch (Exception e)
{
}
}
RunAsync().Wait() 应该怎么做;方法在第一个示例中正确插入,我应该如何调用正确的函数?
编辑:
好的,所以最终我会这样做:
static void Main(string[] args)
{
while (true)
{
try
{
System.Threading.Thread.Sleep(1000);
string signal = ReadGraph(driver, webElement); //////READ CHART
if (signal == "blue")
{
Task.Run(async () => await RunAsync(signal)).Wait();
}
if (signal == "green")
{
RunAsync(signal);
}
}
catch
{
}
}
}
但是,无论何时调用 RunAsync,它都会执行,但线程永远不会返回到主循环。 我试过了
Task.Run(async () => await RunAsync(signal)).Wait()
Task.Run(async () => await RunAsync(signal)).Wait()
RunAsync(signal);
RunAsync(signal).wait();
同样的结果,我做错了什么?
【问题讨论】:
-
打电话给
RunAsync().Wait()真是太浪费了。如果您要取消异步异步,为什么不使用Run方法? -
感谢@Enigmativity 我已经发布了我的尝试更新,因为我不完全确定如何做到这一点
-
不要使用
.Wait()。如果你这样做,使用async毫无意义。 -
调用
Task.Run(async () => await RunAsync(signal)).Wait()就像进行 3 次嵌套的async调用,但随后将所有这些都丢弃并等待结果。您最好只使用一个名为Run的方法,而不使用async。 -
哦,对了,我现在明白了,我基本上只是做了一个
static void Run()并且简单地调用它似乎工作正常。非常感谢!
标签: c# asynchronous httpclient