轮询任务 [英] Polling with a task

查看:136
本文介绍了轮询任务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,

我对Task或TPL相当陌生,而且我不是专业的程序员。我能够直接使用Threads做同样的事情。我不知道我的解决方案是否是一个好的做法,但是它有效并且仍然可以正常工作。

I'm fairly new to the Task or TPL and I'm not a programmer by profession. I was able to do the same thing using Threads directly. I don't know if my solution was of a good practice, but however it worked and still works just fine.

为了使新项目的代码更好的研究,我注意到大多数情况下任务是一个更好的选择,所以我试试看。我阅读了一些网页并观看了一些教程,但我越来越困惑。

In research to make the code for a new project better I noticed that in most cases Tasks are a better choice, so I just give it a try. I read some web pages and watch a few tutorial but I was getting more and more confused.

我想要实现的目标之一是使用某个库中的客户端对象进行简单的池化,定期读取数据,如果存在任何更改,则触发事件。这就是为什么我创建一个长时间运行的任务,执行一个定期
读取数据的函数,并在必要时触发表示该值已被更改的事件。我在下面添加了一个示例代码,这只是为了得到一个想法,我是如何尝试的。因此,为了能够停止任务,我将取消令牌添加为函数的输入
参数。我还添加了定期检查是否有请求取消。到目前为止,代码工作得很好,但我不知道这是否正确,所以我愿意接受建议。我本来可以用一个计时器(也许是
我甚至会。),但我只想尝试一下任务。 

One of the goals I want to achieve is a simple pooling using a client object from some library, to periodicaly read the data and if any changed exists triggers the event. So that's why I created a long running task that executes a function that periodically reads data and if necessary trigger the event which signals that the value has been changed. I added a sample code bellow, which is just to get an idea, how I'm attempting to do it. So in order to be able to stop the Task I added cancellation token as an input parameter to the function. I also added the periodical checking if there is a cancelation requested. To that point the code works just fine, but I don't know if that's the right approach so I'm open for suggestions. I could have used a timer for all that (Maybe I even will.), but I just want to give it a try with a Task. 

所以顺序为了能够停止Pooling我实现了一个在TokenSource上调用Cancel()的函数,但我希望该函数等待Task完成而不会阻塞它被调用的线程,但是我无法做到这一点。

So in order to be able to stop the Pooling I implemented a function that calls Cancel() on the TokenSource, but I want that function to wait for the Task to finish without blocking the thread that it was called on but I'm unable to do that.

当我试图理解Taks的原理时,我越是困惑越多,现在我就是不能得到它,Async,Await等等。

As I try to understand the principles of Taks the more the more confused I'm and for now I just don't get it, Async, Await and so on.

所以如果有人可以将几行放在我的案例中,我会很高兴,所以我可以修改它以满足我的需要并尝试理解它。

So I would be pleased if somebody can put a few lines together that would work for my case, so I can modify it to suit my needs and try to understand it.

public class
{
	Task readTask;
	CancellationTokenSource cancelationTokenSourceReadTask;
	CancellationToken tokenReadTask;
	object syncObject;
	
	public void StartReading()
        {
            cancelationTokenSourceReadTask = new CancellationTokenSource();
            tokenReadTask = cancelationTokenSourceReadTask.Token;

            readTask = Task.Factory.StartNew(() => { ReadVariables(tokenReadTask); }, tokenReadTask, TaskCreationOptions.LongRunning, TaskScheduler.Default);
        }
		
	public void StopReading()
        {
            cancelationTokenSourceReadTask.Cancel();
			
			// In here I would like to wait for the Task to finish whithout blocking the thread that this function is executed on.
			// Not realy necesarry in that case, but it can be useful for my other stuff for which I will use a task and takse longer to finish/cancel.
        }
		
	private void ReadVariables(CancellationToken token)
	{
		while (true)
		{
			// Check if cancelation is requested.
			if (token.IsCancellationRequested)
			{
				break;
			}

			int readResult;

			// Reading using a client. I also use the same client to write, so thats why I used lock.
			lock (syncObject)
			{
				// Read data. 
				// Async method for reading the data is not available.
			}

			// If necesarry trigger the event to notify the subscribers that the data has been changed.
		}
	}
}

推荐答案

您好Primoz29,

Hi Primoz29,

感谢您发布此处。

对于您的问题,您的意思是您想在代码中使用async await吗?如果你想在  ReadVariables方法中使用async await,你想要等待并返回什么? 

For your question, do you mean you want to use async await in your code? If you want to use async await in ReadVariables method, what you want to await and return? 

如果你没有等待的事情,那么 ReadVariables方法,不需要使用async await。

If you do not have something to await in ReadVariables method, there is no need t use async await.

为了更好地理解,这里有一个简单的async等待你的参考示例。

For better understanding, here is a simple example of async await for your reference.

  static void Main(string[] args)
        {
            Console.WriteLine("MainThread,ThreadID:{0}", Thread.CurrentThread.ManagedThreadId);
            TestAsync();
            Console.ReadLine();
        }

        static async Task TestAsync()
        {
            Console.WriteLine("Before invoking GetReturnResult(), ThreadID:{0}. Current Time:{1}", Thread.CurrentThread.ManagedThreadId, DateTime.Now.ToString("yyyy-MM-dd hh:MM:ss"));
            var name = GetReturnResult();
            Console.WriteLine("After invoking GetReturnResult(), ThreadID:{0}. Current Time:{1}", Thread.CurrentThread.ManagedThreadId, DateTime.Now.ToString("yyyy-MM-dd hh:MM:ss"));
            Console.WriteLine("GetReturnResult() Result:{0}. Current Time:{1}", await name, DateTime.Now.ToString("yyyy-MM-dd hh:MM:ss"));
        }

        static async Task<string> GetReturnResult()
        {
            Console.WriteLine("Before running Task.Run, ThreadID:{0}", Thread.CurrentThread.ManagedThreadId);
            return await Task.Run(() =>
            {
                Thread.Sleep(3000);
                Console.WriteLine("GetReturnResult() ThreadID: {0}", Thread.CurrentThread.ManagedThreadId);
                return "Return Value";
            });
        }






最好的问候,

Wendy


这篇关于轮询任务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆