返回类型为list的方法可以从线程中调用吗?

本文关键字:线程 调用 list 方法 返回类型 | 更新日期: 2023-09-27 18:11:52

我有一个方法,如下所示,它调用一个服务。

如何在线程中运行这个方法?

public List<AccessDetails> GetAccessListOfMirror(string mirrorId,string server)
{
    List<AccessDetails> accessOfMirror = new List<AccessDetails>();
    string loginUserId = SessionManager.Session.Current.LoggedInUserName;
    string userPassword = SessionManager.Session.Current.Password;
    using (Service1Client client = new Service1Client())
    {
        client.Open();
        accessOfMirror = client.GetMirrorList1(mirrorId, server, null);
    }
    return accessOfMirror;
}

返回类型为list的方法可以从线程中调用吗?

在c# 3.5或4.0中可以这样做。

var task = Task.Factory.StartNew<List<AccessDetails>>(() => GetAccessListOfMirror(mirrorId,server))
.ContinueWith(tsk => ProcessResult(tsk));
private void ProcessResult(Task task)
{
    var result = task.Result;
}

在c# 4.5中有await/async关键字,这是上面的一些糖

public async Task<List<AccessDetails>> GetAccessListOfMirror(string mirrorId,string server)
var myResult = await GetAccessListOfMirror(mirrorId, server)

试试这样:

public async Task<List<AccessDetails>> GetAccessListOfMirror(string mirrorId, string server)
    {
        List<AccessDetails> accessOfMirror = new List<AccessDetails>();
        string loginUserId = SessionManager.Session.Current.LoggedInUserName;
        string userPassword = SessionManager.Session.Current.Password;

        using (Service1Client client = new Service1Client())
        {
            client.Open();
            Task<List<AccessDetails>> Detail = client.GetMirrorList1(mirrorId, server, null);
            accessOfMirror = await Detail;
        }

        return accessOfMirror;
    }

下面是我使用的一个helper类,它引用了RX.NET。

如果你把它包含在你的项目中,那么你可以非常简单地线程化的东西-上面的代码你可以旋转到一个单独的线程,如下所示:

int mirrorId = 0;
string server = "xxx";
ASync.Run<List<AccessDetails>>(GetAccessListOfMirror(mirrorId,server), resultList => {
   foreach(var accessDetail in resultList)
   {
         // do stuff with result
   }
}, error => { // if error occured on other thread, handle exception here  });

值得注意的是: lambda表达式被合并回原始调用线程-如果您从GUI线程初始化您的异步操作,这是非常方便的。

它还有另一个非常方便的方法:Fork允许你分离多个工作线程,并导致调用线程阻塞,直到所有子线程完成或出错。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Concurrency;
namespace MyProject
{
    public static class ASync
    {
        public static void ThrowAway(Action todo)
        {
            ThrowAway(todo, null);
        }
        public static void ThrowAway(Action todo, Action<Exception> onException)
        {
            if (todo == null)
                return;
            Run<bool>(() =>
            {
                todo();
                return true;
            }, null, onException);
        }
        public static bool Fork(Action<Exception> onError, params Action[] toDo)
        {
            bool errors = false;
            var fork = Observable.ForkJoin(toDo.Select(t => Observable.Start(t).Materialize()));
            foreach (var x in fork.First())
                if (x.Kind == NotificationKind.OnError)
                {
                    if(onError != null)
                        onError(x.Exception);
                    errors = true;
                }
            return !errors;
        }
        public static bool Fork<T>(Action<Exception> onError, IEnumerable<T> args, Action<T> perArg)
        {
            bool errors = false;
            var fork = Observable.ForkJoin(args.Select(arg => Observable.Start(() => { perArg(arg); }).Materialize()));
            foreach (var x in fork.First())
                if (x.Kind == NotificationKind.OnError)
                {
                    if (onError != null)
                        onError(x.Exception);
                    errors = true;
                }
            return !errors;
        }

        public static void Run<TResult>(Func<TResult> todo, Action<TResult> continuation, Action<Exception> onException)
        {
            bool errored = false;
            IDisposable subscription = null;
            var toCall = Observable.ToAsync<TResult>(todo);
            var observable =
                Observable.CreateWithDisposable<TResult>(o => toCall().Subscribe(o)).ObserveOn(Scheduler.Dispatcher).Catch(
                (Exception err) =>
                {
                    errored = true;
                        if (onException != null)
                            onException(err);

                        return Observable.Never<TResult>();
                }).Finally(
                () =>
                {
                    if (subscription != null)
                        subscription.Dispose();
                });
            subscription = observable.Subscribe((TResult result) =>
            {
                if (!errored && continuation != null)
                {
                    try
                    {
                        continuation(result);
                    }
                    catch (Exception e)
                    {
                        if (onException != null)
                            onException(e);
                    }
                }
            });
        }
    }
}