我正在开发一个代码,该代码定期截取图像的网页,扫描图像的像素颜色,如果找到颜色,则异步连接到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();
同样的结果,我做错了什么?
答案 0 :(得分:0)
如果你想async
:
static async void Main(string[] args)
{
while (true)
{
await Task.Delay(TimeSpan.FromSeconds(1.0));
string signal = ReadGraph(driver, webElement);
if (signal == "blue")
{
await RunAsync(signal);
}
if (signal == "green")
{
await RunAsync(signal);
}
}
}