I am writing a very simple asynchronous helper class to go along with my project. The purpose of the class is that it allows you to use the method in the background thread. Here is the code:
internal class AsyncHelper { private readonly Stopwatch timer = new Stopwatch(); internal event DownloadCompleteHandler OnOperationComplete; internal void Start(Func func, T arg) { timer.Start(); func.BeginInvoke(Done, func); } private void Done(IAsyncResult cookie) { timer.Stop(); var target = (Func) cookie.AsyncState; InvokeCompleteEventArgs(target.EndInvoke(cookie)); } private void InvokeCompleteEventArgs(T result) { var args = new EventArgs(result, null, AsyncMethod.GetEventByClass, timer.Elapsed); if (OnOperationComplete != null) OnOperationComplete(null, args); } #region Nested type: DownloadCompleteHandler internal delegate void DownloadCompleteHandler(object sender, EventArgs e); #endregion }
The result of the task is then returned through the OnOperationComplete event. The problem is that when the event rises, it is still in the background thread. That is, if I try to run this code (below), I get a cross-thread error;
txtOutput.AppendText(e.Result + Environment.NewLine);
Please communicate any thoughts.
generics c # asynchronous events delegates
user405783
source share